leetcode---generate-parentheses---dfs

来源:互联网 发布:trivium算法 编辑:程序博客网 时间:2024/06/11 13:49

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
“((()))”, “(()())”, “(())()”, “()(())”, “()()()”

class Solution {public:    bool ok(string &s)    {        int cnt = 0;        for(int i=0; i<s.size(); i++)        {            if(s[i] == '(')                cnt++;            else                cnt--;            if(cnt < 0)                return false;        }        return cnt == 0;    }    void dfs(int dep, int n, string s, vector<string> &ans)    {        if(dep >= n)        {            if(ok(s))                ans.push_back(s);            return;        }        dfs(dep+1, n, s+'(', ans);        dfs(dep+1, n, s+')', ans);    }    vector<string> generateParenthesis(int n)     {        vector<string> ans;        string s = "";        dfs(0, n+n, s, ans);        return ans;    }};
原创粉丝点击