• [Leetcode 49] 22 Generate Parentheses


    Problem:

    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:

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

    Analysis:

    Also a backtracking problem. Each time either put a '(' or ')' into the current stack.

    There's a optimization we can do, a well-formed parentheses must have the same number of '(' and ')', either one exceeds half of the n*2, it won't become a valid solution. So we can prune it as early as possible.

    Code:

     1 class Solution {
     2 public:
     3     vector<string> res;
     4     int total;
     5     
     6     vector<string> generateParenthesis(int n) {
     7         // Start typing your C/C++ solution below
     8         // DO NOT write int main() function
     9         //res.clear();
    10         total = n*2;
    11         res.clear();
    12         bc("(", 1, 0);
    13         
    14         return res;
    15     }
    16     
    17     void bc(string path, int left, int right) {
    18         if (left > total/2 || right > total/2)
    19             return ;
    20         
    21         if (path.size()==total && valid(path)) {
    22             res.push_back(path);
    23             return ;
    24         }
    25         
    26         bc(path+")", left, right+1);
    27         bc(path+"(", left+1, right);
    28         return ;
    29     }
    30     
    31     bool valid(string s) {
    32         int cnt = 1;
    33         for (int i=1; i<s.size(); i++) {
    34             if (s[i] == '(') cnt++;
    35             if (s[i] == ')') cnt--;
    36             
    37             if (cnt < 0) return false;
    38         }
    39         
    40         return true;
    41     }
    42 };
    View Code
  • 相关阅读:
    [51nod1299]监狱逃离
    [51nod1206]Picture
    noi 2016 游记
    [Codeforces 696D] Legen...
    [bzoj2574] [Poi1999]Store-Keeper
    [bzoj1227] [SDOI2009]虔诚的墓主人
    [bzoj3979] [WF2012]infiltration
    Docker
    SpringBoot实现登录
    SpringBoot第一次案例
  • 原文地址:https://www.cnblogs.com/freeneng/p/3098753.html
Copyright © 2020-2023  润新知