1 class Solution 
 2 {
 3 public:
 4     vector<string> generateParenthesis(int n) 
 5     {
 6         vector<string> res;
 7         string cur;
 8         helper(cur,0,0,n,res);
 9         return res;
10     }
11     
12     void helper(string &cur,int left,int right,int n,vector<string> &res)
13     {
14         if(left==n&&right==n)
15         {
16             res.push_back(cur);
17             return ;
18         }        
19         if(left<n)
20         {
21             cur.push_back('(');
22             helper(cur,left+1,right,n,res);
23             cur.pop_back();
24         }
25         if(left>right)
26         {
27             cur.push_back(')');
28             helper(cur,left,right+1,n,res);
29             cur.pop_back();
30         }
31     }
32 };

当左括号数量小于n时可以添加左括号,当左括号数量大于右括号数量时可以添加右括号

这里用了递归,并且在递归中,cur使用的是引用,节约了时间。值得注意的是,返回上一层递归时,cur要删除末尾添加的元素

posted on 2018-07-06 13:26  高数考了59  阅读(177)  评论(0)    收藏  举报