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:

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

    利用一个递归函数来产生,用一个参数来记录当前剩下可对应的左扩号数,只有leftNum > 0,才能加入右括号,同时增加一些剪支,例如leftNumTotal > n时说明左括号太多了,不可能产生合理解。

     1 class Solution {
     2 private:
     3     vector<string> ret;
     4 public:
     5     void solve(int dep, int maxDep, int leftNum, int leftNumTotal, string s)
     6     {
     7         if (leftNumTotal * 2 > maxDep)
     8             return;
     9             
    10         if (dep == maxDep)
    11         {
    12             ret.push_back(s);
    13             return;
    14         }
    15         
    16         for(int i = 0; i < 2; i++)
    17             if (i == 0)
    18             {
    19                 solve(dep + 1, maxDep, leftNum + 1, leftNumTotal + 1, s + '(');
    20             }
    21             else
    22             {
    23                 if (leftNum > 0)
    24                     solve(dep + 1, maxDep, leftNum - 1, leftNumTotal, s + ')');
    25             }
    26     }
    27     
    28     vector<string> generateParenthesis(int n) {
    29         // Start typing your C/C++ solution below
    30         // DO NOT write int main() function
    31         ret.clear();
    32         solve(0, 2 * n, 0, 0, "");
    33         return ret;
    34     }
    35 };
  • 相关阅读:
    为什么需要域驱动设计(DDD)?
    什么是无所不在的语言?
    什么是耦合?
    什么是 Spring Cloud?
    你更倾向用那种事务管理类型?
    您对微服务有何了解?
    微服务架构有哪些优势?
    微服务架构如何运作?
    @Qualifier 注解 ?
    JdbcTemplate ?
  • 原文地址:https://www.cnblogs.com/chkkch/p/2757711.html
Copyright © 2011-2022 走看看