Generate Parentheses

2014-11-24 08:59:05 · 作者: · 浏览: 0
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
java code : 采用递归树的思想,当左括号数大于右括号数时可以加左或者右括号,否则只能加左括号,当左括号数达到n时,剩下全部
加右括号。
public class Solution {  
    public ArrayList generateParenthesis(int n) {  
        // Note: The Solution object is instantiated only once and is reused by each test case.  
        ArrayList
res = new ArrayList(); generate(res, "", 0, 0, n); return res; } public void generate(ArrayList res, String tmp, int lhs, int rhs, int n) { if(lhs == n) { for(int i = 0; i < n - rhs; i++) { tmp += ")"; } res.add(tmp); return ; } generate(res, tmp + "(", lhs + 1, rhs, n); if(lhs > rhs) generate(res, tmp + ")", lhs, rhs + 1, n); } }