22. Generate Parentheses QuestionEditorial Solution

来源:互联网 发布:unity3d 积木游戏 编辑:程序博客网 时间:2024/06/06 03:31

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:

[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]

思路:排列组合,用DFS, 本质上就是排列(和),配对n次。满足的规则是从(开始,并且剩下的(的个数一定要小于剩下的)的个数。

class Solution {public:    vector<string> generateParenthesis(int n) {        vector<string> ans;        if(n <= 0) return ans;        string tmp = "";        dfs(ans,tmp,n,n); //最开始左右各剩下n个没有print        return ans;    }    void dfs(vector<string> &ans, string tmp, int left, int right)    {        if(left==0 && right==0)        {            ans.push_back(tmp);            return;        }        if(left > 0) dfs(ans, tmp+"(", left-1, right);        if(left<right) dfs(ans, tmp+")", left, right-1);    }};
0 0
原创粉丝点击