leetcode [#22]

目录

题目

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

For example, given n = 3, a solution set is:

[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]


解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
recursivelyGetParenthesis(res, "", 0, 0, n);
return res;
}
private static void recursivelyGetParenthesis(List<String> list, String s, int left, int right, int n){
if(s.length() == n * 2) {
list.add(s);
return;
}
if(left < n) recursivelyGetParenthesis(list, s + "(", left + 1, right, n);
if(right < left) recursivelyGetParenthesis(list, s + ")", left, right + 1, n);
}
}

注意事项

  1. 不应该从找规律的角度入手,这样即便得到可能情况的总数,但生成具体字符串时还比较麻烦。
  2. recursivelyGetParenthesis()方法的作用是,逐步生成结果字符串,当长度满足时就作为一个符合要求的结果返回,否则,在当前片段的基础上递归调用自身,生成新的结果。