1
1
/* Generate Parentheses:Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.*/
2
+ // 一开始left = n,right = 0;当left还剩余左括号数大于0的时候,添加左括号,并将left – 1,right + 1;
3
+ // 当right目前还需要的右括号数大于0的时候,添加右括号,并将right – 1;
4
+ // 当left和right都等于0的时候,表示当前是一个符合格式条件的字符串,将该字符串cur放入result数组中,最后返回result。
2
5
class Solution {
3
6
public:
4
7
vector<string> generateParenthesis (int n) {
5
- vector<string> rs;
6
- string s;
7
- genParenthesis (rs, s, n, n);
8
- return rs;
8
+ dfs (" " , n, 0 );
9
+ return result;
10
+ }
11
+ private:
12
+ vector<string> result;
13
+ void dfs (string cur, int left, int right) {
14
+ if (left == 0 && right == 0 ) {
15
+ result.push_back (cur);
16
+ return ;
17
+ }
18
+ if (left > 0 ) dfs (cur + " (" , left - 1 , right + 1 );
19
+ if (right > 0 ) dfs (cur + " )" , left, right - 1 );
9
20
}
10
- void genParenthesis (vector<string> &rs, string &s, int left, int right)
11
- {
12
- if (left==0 )
13
- {
14
- rs.push_back (s);
15
- rs.back ().append (right, ' )' );
16
- return ;
17
- }
18
- s.push_back (' (' );
19
- genParenthesis (rs, s, left-1 , right);
20
- s.pop_back ();
21
- if (left < right)
22
- {
23
- s.push_back (' )' );
24
- genParenthesis (rs, s, left, right-1 );
25
- s.pop_back ();
26
- }
27
- }
28
21
};
0 commit comments