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:
"((()))", "(()())", "(())()", "()(())", "()()()"
public class Solution { public List<String> generateParenthesis(int n) { int left=0; int right=0; String str=""; List<String> list =new ArrayList<String>(); gen(left, right, n, str, list); return list; } public void gen(int left, int right, int n, String str, List<String> list){ if( left==n && right==n){ list.add(str); return; } if( left<n && left==right){ gen(left+1, right, n,str+"(", list); } else if( left<n && left>right ){ gen(left+1, right, n,str+"(", list); gen(left, right+1, n,str+")", list); } else if(left==n && right<n ){ gen(left, right+1, n,str+")", list); } } }主要用到了递归的思想,递归时保证字符串中左括号数大于等于右括号数即可。
Generate Parentheses,布布扣,bubuko.com
原文地址:http://blog.csdn.net/dutsoft/article/details/37700647