zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    等待通知--wait notify
    表单重复提交与解决
    Cookie Session 与Token
    springMVC实现登陆
    第11章 AOF持久化
    第10章 RDB持久化
    MyBatis动态SQL
    第4章 网络层
    第9章 数据库
    代理设计模式
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6401029.html
Copyright © 2011-2022 走看看