Skip to content

Commit 3f2c98f

Browse files
author
Li Li
committed
add code of 22
1 parent 2f0482e commit 3f2c98f

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/*
2+
In general, for each bit, we can choose either "(" or ")", but in this problem.
3+
To get paired solution, for each bit site, there are some restrictions.
4+
To add "(": there must be some "(" remaining.
5+
To add ")": 1, there must be some "(" remaining.
6+
2, previous acount of "(" must be more than ")".
7+
1 + 2 => remainning "(" less than ")"
8+
9+
*/
10+
public class Solution {
11+
public IList<string> GenerateParenthesis(int n) {
12+
IList<string> result = new List<string>();
13+
if (n > 0) DFSHelper(result, "", n, n);
14+
return result;
15+
}
16+
private void DFSHelper(IList<string> result, string s, int left, int right) {
17+
if (left == 0 && right == 0) result.Add(s);
18+
// has remaining "("
19+
if (left > 0) DFSHelper(result, s + "(", left - 1, right);
20+
// has more ")" remain
21+
if (right > 0 && right > left) DFSHelper(result, s + ")", left, right - 1);
22+
}
23+
}

0 commit comments

Comments
 (0)