zoukankan      html  css  js  c++  java
  • Leetcode-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:

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

    Have you met this question in a real interview?
     
    Analysis:
    We define the subproblem as if we now have n left parenthese and m right parenthese, how to generate all legal output.
    1. We can always put a left parenthese, and then solve the subproblem with n-1 and m.
    2. We can put a right parenthese here only if m>n, otherwise, the output violate the mathcing rule. If we put a right parenthese, we then solve the subproblem with n and m-1.
     
    Solution:
     1 public class Solution {
     2     public List<String> generateParenthesis(int n) {
     3         List<String> resSet = new ArrayList<String>();
     4         if (n==0) return resSet;
     5         String curStr = "";
     6         parenthesisRecur(curStr,n,n,resSet);
     7         return resSet;
     8     }
     9 
    10     public void parenthesisRecur(String curStr, int n, int m, List<String> resSet){
    11         if (n==0 && m==0){
    12             resSet.add(curStr);
    13             return;
    14         }
    15 
    16         if (n>0){
    17             curStr = curStr+"(";
    18             parenthesisRecur(curStr,n-1,m,resSet);
    19             curStr = curStr.substring(0,curStr.length()-1);
    20         }
    21 
    22         if (m>n){
    23             curStr=curStr+")";
    24             parenthesisRecur(curStr,n,m-1,resSet);
    25             curStr = curStr.substring(0,curStr.length()-1);
    26         }
    27 
    28     }
    29 }
  • 相关阅读:
    构建之法阅读笔记06
    构建之法阅读笔记05
    人月神话阅读笔记02
    人月神话阅读笔记01
    构建之法阅读笔记04
    学习进度09
    描绘用户场景并将典型用户和用户场景描述
    学习进度08
    第一冲刺阶段工作总结11
    第一冲刺阶段工作总结10
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4111924.html
Copyright © 2011-2022 走看看