zoukankan      html  css  js  c++  java
  • 【leetcode】Generate Parentheses

    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:

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

     
     
    用递归生成所有的括号组合,并且在递归过程中不断剪枝
    剪枝的条件:
     leftNum>n||rightNum>n||rightNum>leftNum)
    1.左、右括号数目大于了n
    2.右括号数目大于了左括号数目
     
     
     1 class Solution {
     2 
     3 public:
     4 
     5     vector<string> generateParenthesis(int n) {
     6 
     7        
     8 
     9         vector<string> result;
    10 
    11         generate(result,"",0,n,0,0);
    12 
    13         return result;
    14 
    15        
    16 
    17     }
    18 
    19    
    20 
    21     void generate(vector<string> &result,string tmp,int index,int &n,int leftNum,int rightNum)
    22 
    23     {
    24 
    25         if(leftNum>n||rightNum>n||rightNum>leftNum)
    26 
    27         {
    28 
    29             return;
    30 
    31         }
    32 
    33         if(index==2*n)
    34 
    35         {
    36 
    37             result.push_back(tmp);
    38 
    39             return;
    40 
    41         }
    42 
    43        
    44 
    45         generate(result,tmp+"(",index+1,n,leftNum+1,rightNum);
    46 
    47         generate(result,tmp+")",index+1,n,leftNum,rightNum+1);
    48 
    49     }
    50 
    51 };
  • 相关阅读:
    数据类型
    python安装
    计算机基础
    Ajax--1
    ASP.net+MVC--2
    More lumber is required
    History Grading
    strcmp() Anyone?
    How Many Points of Intersection?
    Remember the Word
  • 原文地址:https://www.cnblogs.com/reachteam/p/4192433.html
Copyright © 2011-2022 走看看