lintcode - 生成括号

 1 class Solution {
 2 public:
 3     /*
 4      * @param n: n pairs
 5      * @return: All combinations of well-formed parentheses
 6      */
 7     vector<string> generateParenthesis(int n) {
 8         // write your code here
 9         vector<string> ans;
10         dfs(0, 0, "", ans, n);
11         return ans;
12     }
13     void dfs(int left, int right, string res, vector<string> &ans, int n){
14         if(left < right || (left > n || right > n)) return ;
15         if(left == n && right == n){
16                 ans.push_back(res);
17                 return ;
18         }
19         string tmp = res;
20         string tmp1 = res;
21         tmp += ')';
22         tmp1 += '(';
23         dfs(left, right + 1, tmp, ans, n);
24         dfs(left + 1, right, tmp1, ans, n);
25 
26     }
27 };

右边的括号不能比左边多

posted @ 2017-09-25 19:02 GeniusYang 阅读(...) 评论(...) 编辑 收藏