generate-parentheses

2019-10-04  本文已影响0人  DaiMorph

保证左边‘(’的数量始终大于等于右边的‘)’数量,可以考虑回溯法

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string>ans;
        dfs("",0,0,n,ans);
        return ans;
    }
    void dfs(string out,int left,int right,int n,vector<string>&ans)
    {
        if(left>n||right>n)return;
        if(right==n){
            ans.push_back(out);
            return;
        }
        dfs(out+"(",left+1,right,n,ans);
        if(left>right)dfs(out+")",left,right+1,n,ans);
    }
};
上一篇下一篇

猜你喜欢

热点阅读