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:

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

    Analyse: As long as number of "(" is smaller than n, we can push "(", as long as number of ")" is smaller than "(", we can push ")". 

    Runtime: 0ms.

     1 class Solution {
     2 public:
     3     vector<string> generateParenthesis(int n) {
     4         vector<string> result;
     5         if(!n) return result;
     6         
     7         helper(n, 0, 0, result, "");
     8         return result;
     9     }
    10     
    11     void helper(int n, int left, int right, vector<string>& result, string temp) {
    12         if(left == n && right == n) {
    13             result.push_back(temp);
    14             return;
    15         }
    16         if(left < n) helper(n, left + 1, right, result, temp + "(");
    17         if(right < left && right < n) helper(n, left, right + 1, result, temp + ")");
    18     }
    19 };
  • 相关阅读:
    HTTP
    nginx反向代理和负载均衡
    keepalive
    lnmp
    DNS
    jumpserver跳板机
    博客已搬家到CSDN
    JAVA中关于上传图片到数据库和从数据库取出显示图片的问题
    checkbox的标签和全选中问题
    SOCKET
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/5755006.html
Copyright © 2011-2022 走看看