括号生成

class Solution {
public:
    void dfs(int n, int left, int right, string path, vector<string>& res){
        if(right==n){
            res.push_back(path);
            return;
        }

        if(left<n){
            dfs(n,left+1,right,path+"(",res);
        }
        if(right<left){
            dfs(n,left,right+1,path+")",res);
        }

    }

    vector<string> generateParenthesis(int n) {
        if(n==0) return {};

        string path="";
        vector<string> res;

        dfs(n,0,0,path,res);

        return res;
    }
};

 

posted @ 2020-03-07 17:24  7aughing  阅读(160)  评论(0编辑  收藏  举报