problem

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

1
2
3
4
5
6
7
8
9
For example, given n = 3, a solution set is:

[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

approach1

深度优先搜索

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
helper(res, "", n, 0, 0);
return res;

}

private void helper(List<String> res, String s, int n, int left, int right) {
if (right == n) {
res.add(s);
return;
}

if (left < n) {
helper(res, s + "(", n, left + 1, right);
}
if (right < left) {
helper(res, s + ")", n, left, right + 1);
}
}
}
  • time:O(n!) O(2^n) 卡特兰数
  • space:O(n)

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×