题目:
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:
“((()))”, “(()())”, “(())()”, “()(())”, “()()()”
方法一思路:
通过递归的方式,对于f(n) 先求得f(n-1)的结果,那会对结果中的每一项的各个位置插入”()”
public class Solution {
public List<String> generateParenthesis(int n) {
Set<String> res = new HashSet<> ();
if(n < 1) return new ArrayList<String> (res);
if(n == 1) {
res.add("()");
return new ArrayList<String> (res);
}
// 得到n-1的结果
List<String> pre = generateParenthesis(n - 1);
for(String s : pre) {
// 插入"()"不要担心重复 因为set
for(int j = 0 ; j < s.length() ; j++) {
res.add(s.substring(0 , j) + "()" + s.substring(j));
}
res.add(s.substring(0) + "()");
}
return new ArrayList<String> (res);
}
}
方法二:
来源 : Generate Parentheses – LeetCode
DFS: 可以通过树形结构描叙整个过程. **树中每一条路径就是一种可能!左孩子就是”(” , 右孩子就是“)” ;
实际上,这也可以看成是构造一颗满二叉树的过程!**
在每次递归函数中记录左括号和右括号的剩余数量,然后有两种选择,一个是放一个左括号,另一种是放一个右括号。当然有一些否定条件,比如剩余的右括号不能比左括号少,或者左括号右括号数量都要大于0。正常结束条件是左右括号数量都为0。
public ArrayList<String> generateParenthesis(int n) {
ArrayList<String> res = new ArrayList<String>();
if(n<=0)
return res;
helper(n,n,new String(),res);
return res;
}
private void helper(int l, int r, String item, ArrayList<String> res)
{
if(r<l) // 这不是合法的
return;
if(l==0 && r==0)
{
res.add(item);
}
if(l>0)
helper(l-1,r,item+"(",res);
if(r>0)
helper(l,r-1,item+")",res);
}