zoukankan      html  css  js  c++  java
  • 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) 限制: 比如 越界等
    if (左右括号都已用完) {


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

      

  • 相关阅读:
    linux下编译sphinx拓展
    Java为什么使用连接池
    内部类之.this&&.new
    何为代理
    Qt install Phonon
    Gcc简介与常用命令
    Vim的设置和使用——编程者
    QT程序启动界面的使用
    slide from one widget to another
    Hide the common top menu in Ubuntu 12.04
  • 原文地址:https://www.cnblogs.com/superzhaochao/p/6400436.html
Copyright © 2011-2022 走看看