22. 括号生成(c++)

在这里插入图片描述
在这里插入图片描述
当前左右括号都有小于n个可以使用的时候,才产生分支;
产生左分支的时候,只看当前是否还有左括号可以使用;
产生右分支的时候,还受到左分支的限制,右边剩余可以使用的括号数量一定得在严格小于左边剩余的数量的时候,才可以产生分支;
在左边和右边剩余的括号数都等于 n的时候结算。
一、

#include<iostream>
#include<stdio.h>
#include<vector>
#include<string>
using namespace std;
 
class Solution {
    void dfs(vector<string>& ans, string cur, int left, int right, int n) {
        if (left == n && right == n) {//在左边和右边剩余的括号数都等于 n的时候结算。
            ans.push_back(cur);
            return;
        }
        if(left < right){//右边剩余可以使用的括号数量一定得在严格小于左边剩余的数量的时候,才可以产生分支
            return ;//直接返回,剪支
        }
        if (left< n) {
            dfs(ans, cur+'(', left + 1, right, n);//左括号都有小于n个,产生分支
        }
        if (right < n) {
            dfs(ans, cur+')', left, right + 1, n);//右括号都有小于n个,产生分支
        }
    }
public:
    vector<string> generateParenthesis(int n) {
        vector<string> result;
        string current = "";
        // 特判
        if (n == 0) {
            return result;
        }
        dfs(result, current, 0, 0, n);
        return result;
    }
};

 
int main()
{
	int n = 3;
    vector<string>res;
    Solution s;
    res = s.generateParenthesis(n);
    for(string c:res){
        cout << c << " ";
    }
 
	return 0;
}

二、

class Solution {
    void dfs(vector<string>& ans, string& cur, int left, int right, int n) {
        if (left == n && right == n) {
            ans.push_back(cur);
            return;
        }
        if(left < right){
            return ;
        }
        if (left< n) {
            cur.push_back('(');//相当于cur += ‘(’
            dfs(ans, cur, left + 1, right, n);
            cur.pop_back();//下次再用时,需要pop_back加的’(‘
        }
        if (right < n) {
            cur.push_back(')');
            dfs(ans, cur, left, right + 1, n);
            cur.pop_back();
        }
    }
public:
    vector<string> generateParenthesis(int n) {
        vector<string> result;
        string current;
        // 特判
        if (n == 0) {
            return result;
        }
        dfs(result, current, 0, 0, n);
        return result;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值