22. Generate Parentheses
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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
本题开始做的时候以为用栈比较好,但是做错了,后来看了discussion 发现答案解法很好。用了两个open,close来做为假想的栈,代码如下:
1 public class Solution { 2 public List<String> generateParenthesis(int n) { 3 List<String> res = new ArrayList<String>(); 4 backtracking(res,"",0,0,n); 5 return res; 6 } 7 public void backtracking(List<String> res,String word,int open,int close,int max){ 8 if(word.length()==max*2){ 9 res.add(word); 10 return ; 11 }else{ 12 if(open<max){ 13 backtracking(res,word+"(",open+1,close,max); 14 } 15 if(close<open){ 16 backtracking(res,word+")",open,close+1,max); 17 } 18 } 19 } 20 }