当前位置:编程学习 > JAVA >>

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

 

 
补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,