LeetCode——Generate Parentheses

Description:

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

public class Solution {
    
    public void solve(int left, int right, String ans, List<String> res) {
        
        if(left == 0 && right == 0) {
            res.add(ans);
        }
        
        if(left > 0) {
            solve(left-1, right, ans+"(", res);
        }
        
        if(right>0 && left<right) {
            solve(left, right-1, ans+")", res);
        }
        
        
    }
    
    public List<String> generateParenthesis(int n) {
        
        List<String> list = new ArrayList<String>();
        String ans = new String();
        solve(n, n, ans, list);
        
        return list;
    }
}
原文地址:https://www.cnblogs.com/wxisme/p/4870407.html