首页 > 代码库 > leetcode : generate parenthese

leetcode : generate parenthese

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:[

  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

递归思考的三板斧:
(1) 退出条件, return
(2) 选择: 选择适合的解加入结果集中
(3) 限制: 比如 越界等

public class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<String>();
        if(n <= 0) {
            return result;
        }
        helper(result,"", n, n);
        return result;
    }
    
    public void helper(List<String> result, String paren, int left, int right) {
        
        if(left == 0 && right == 0) {
            result.add(paren);
            return;
        }
        //初始化: 必须先打印左括号
        if(left > 0) {
            helper(result, paren+"(", left - 1, right);
        }
        
        //若剩下的left < right, 说明目前临时的答案中左括号比右括号多,此时必须打印右括号,否则会出现
        //类似“((())(”的错误情况
        
        if(left < right && right > 0) {
            helper(result, paren+")", left, right - 1);
        }
       
    }
    
    
    
}

  

leetcode : generate parenthese