• LeetCode


    Generate Parentheses

    2013.12.7 00:49

    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:

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

    Solution:

      If you're familiar with the Catalan Numbers, you'll see it's a typical solution for this problem.

      Since all the combinations are required, we'll use DFS to go through every possible sequence.

      Let's consider the recursion in the following way:

        1. For a sequence of length 2 * n, there're n '(' and n ')'

        2. For a valid sequence, number of '(' will never be less than the number of ')' at any position. If there're more ')' than '(', there must be a mismatch.

        3. Always do the recursion from left to right.

      Time complexity is H(n) * O(n) = C(2 * n, n) / (n + 1) * n, that's roughly O(n!). Space complexity is not sure yet...

    Accepted code:

     1 // 1AC, simple recursion will do, but keep your mind clear or it's easy to get things complicated
     2 class Solution {
     3 public:
     4     vector<string> generateParenthesis(int n) {
     5         // IMPORTANT: Please reset any member data you declared, as
     6         // the same Solution instance will be reused for each test case.
     7         result.clear();
     8         
     9         dfs(n, n, "");
    10         
    11         return result;
    12     }
    13 private:
    14     vector<string> result;
    15     
    16     void dfs(int cl, int cr, string pat) {
    17         if(cl == 0 && cr == 0){
    18             result.push_back(pat);
    19         }
    20         
    21         int i;
    22         if(cl < cr){
    23             if(cl > 0){
    24                 dfs(cl - 1, cr, pat + "(");
    25             }
    26             if(cr > 0){
    27                 dfs(cl, cr - 1, pat + ")");
    28             }
    29         }else if(cl == cr){
    30             if(cl > 0){
    31                 dfs(cl - 1, cr, pat + "(");
    32             }
    33         }else{
    34             return;
    35         }
    36     }
    37 };
  • 相关阅读:
    java多线程api
    java多线程
    java代理
    java程序员常用的linux命令
    java泛型
    java反射
    日期和时间
    java集合
    Nodejs mac版安装
    for in、each; for 、forEach、map
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3462373.html
Copyright © 2020-2023  润新知