Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c196e7a

Browse files
author
fupengfei
committed
12/20 UPDATE
1 parent bd78495 commit c196e7a

File tree

1 file changed

+15
-22
lines changed

1 file changed

+15
-22
lines changed

‎Leetcode/22. Generate Parentheses.cpp

Lines changed: 15 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,21 @@
11
/*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。
25
class Solution {
36
public:
47
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);
920
}
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-
}
2821
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /