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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
参考自:http://blog.csdn.net/yutianzuijin/article/details/13161721
设left为剩下的左括号数,right为剩下的又括号数,当left和right都为0时,结束输出结果,当left>0时可以输出左括号,但是能否输出又括号还得看左括号数和右括号数之间的关系,当left>=right时只能输出左括号,当left<right可以输出右括号。
package leetcode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class leet22 {
public static void main(String[] args) {
List<String> result = new ArrayList<String>();
String str = new String();
leet22 leet = new leet22();
leet.recur(3, 3, str, result);
System.out.println(Arrays.toString(result.toArray()));
}
public void recur(int left,int right,String str,List<String> result){
if(left==0&&right==0){
result.add(str);
}
if(left>0){
recur(left-1,right,str+("("),result);
}
if(right>0&&left<right){
recur(left,right-1,str+(")"),result);
}
}
}