微软高频面试题:Leetcode 22 括号生成 有效括号字符串递归回溯生成

利用括号序列规律,递归回溯生成。

class Solution {
public:
    vector<string> res;
    string path;
    vector<string> generateParenthesis(int n) {
        dfs(0,0,n);
        return res;
    }

    void dfs(int left, int right, int n){
        if(left==n&&right==n){
            res.push_back(path);
            return;
        }
        if(left<=n){
            path+='(';
            dfs(left+1,right,n);
            path.pop_back();
        }
        if(right<=n&&right<left){
            path+=')';
            dfs(left,right+1,n);
            path.pop_back();
        }
    }
};

猜你喜欢

转载自blog.csdn.net/wwxy1995/article/details/108512132