题目
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
思路
这道题可以用广度优先搜索的思想解决。在每个位置,都有可能是左括号或者右括号,关键是找到其中的规律。假设当前还有m个左括号,n个右括号,则下一个位置有三种可能:
1)n = 0,得到一种排列
2)m > 0,左括号
3)n > m,右括号
代码
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<String>();
if(n == 0)
return result;
String permutation = "";
generatePermutation(n, n, permutation, result);
return result;
}
public void generatePermutation(int left, int right, String permutation, List<String> result) {
if(right == 0)
result.add(permutation);
if(left > 0)
generatePermutation(left-1, right, permutation + "(", result);
if(left < right)
generatePermutation(left, right-1, permutation + ")", result);
}
}