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;
    }
}

 

相关文章:

  • 2022-01-15
  • 2021-11-04
  • 2021-08-12
  • 2021-08-19
猜你喜欢
  • 2021-05-06
  • 2021-09-30
  • 2021-06-30
  • 2022-01-12
  • 2021-10-19
  • 2022-02-15
相关资源
相似解决方案