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

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

    New version: 0ms.

     1 class Solution {
     2 private:
     3     void helper(vector<string>& result, string temp, int left, int right, int n){
     4         if(left == n && right == n){
     5             result.push_back(temp);
     6             return;
     7         }
     8         
     9         if(left < n) helper(result, temp + "(", left + 1, right, n);
    10         if(left > right) helper(result, temp + ")", left, right + 1, n);
    11     }
    12 public:
    13     vector<string> generateParenthesis(int n) {
    14         vector<string> result;
    15         helper(result, "", 0, 0, n);
    16         return result;
    17     }
    18 };

    Runtime: 4ms

     1 class Solution {
     2 public:
     3     vector<string> generateParenthesis(int n) {
     4         vector<string> result;
     5         if(n <= 0) return result;
     6         
     7         helper(result, "", n, n);
     8         return result;
     9     }
    10     void helper(vector<string>& result, string temp, int left, int right){
    11         if(left > right) return;
    12         
    13         if(left == 0 && right == 0){
    14             result.push_back(temp);
    15             return;
    16         }
    17         
    18         if(left > 0)
    19             helper(result, temp + "(", left - 1, right);
    20         
    21         if(right > 0)
    22             helper(result, temp + ")", left, right - 1);
    23         
    24     }
    25 };
  • 相关阅读:
    寻找大富翁
    C++ STL sort()函数用法
    众数
    平方因子
    Hdu 1089 A+B for Input-Output Practice (I)
    Hdu 1090 A+B for Input-Output Practice (II)
    Hdu 1083 Courses
    Hdu 1069 Monkey and Banana
    Hdu 1062 Text Reverse
    Hdu 1068 Girls and Boys
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4873282.html
Copyright © 2011-2022 走看看