Leetcode-回溯算法

Leetcode-回溯算法

回溯

22. 括号生成

数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的括号组合。

class Solution {
public:
    vector<string> result;
    void backtracking(vector<string> temp, int n, int nowleft, int nowright){
        if(temp.size() == n * 2){
            string res = "";
            for(int i=0;i<temp.size();i++){
                res += temp[i];
            }
            result.push_back(res);
            return;
        }
        if (nowleft < n){
            temp.push_back("(");
            backtracking(temp,n,nowleft+1,nowright);
            temp.pop_back();
        }
        if(nowright < n && nowright < nowleft){
            temp.push_back(")");
            backtracking(temp,n,nowleft,nowright+1);
            temp.pop_back();
        }
    }
    vector<string> generateParenthesis(int n) {
        vector<string> temp;
        backtracking(temp,n,0,0);
        return result;
    }
};

Leetcode-回溯算法
https://zhangzhao219.github.io/2024/04/14/Leetcode-bkt/
作者
Zhang Zhao
发布于
2024年4月14日
许可协议