• 22. 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:

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

    本题开始做的时候以为用栈比较好,但是做错了,后来看了discussion 发现答案解法很好。用了两个open,close来做为假想的栈,代码如下:
     1 public class Solution {
     2     public List<String> generateParenthesis(int n) {
     3         List<String> res = new ArrayList<String>();
     4         backtracking(res,"",0,0,n);
     5         return res;
     6     }
     7     public void backtracking(List<String> res,String word,int open,int close,int max){
     8         if(word.length()==max*2){
     9             res.add(word);
    10             return ;
    11         }else{
    12             if(open<max){
    13                 backtracking(res,word+"(",open+1,close,max);
    14             }
    15             if(close<open){
    16                 backtracking(res,word+")",open,close+1,max);
    17             }
    18         }
    19     }
    20 }
  • 相关阅读:
    断棍构造过程-波利亚翁方案-中餐馆过程
    狄利克雷过程
    狄利克雷分布
    共轭先验(conjugate prior)
    镜像与文件系统
    Oracle-04
    Oracle-02
    Oracle-01
    认识数据库
    c:forEach的作用
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6401029.html
Copyright © 2020-2023  润新知