zoukankan      html  css  js  c++  java
  • [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
  • 相关阅读:
    uC/OS II原理分析及源码阅读(一)
    并查集回顾
    js中ascii码的转换
    NS2中trace文件分析
    NS2中修改载波侦听范围和传输范围
    ubuntu wubi非在线快速安装
    用康托展开实现全排列(STL、itertools)
    日期的各种计算
    求约数的个数(约数个数定理)
    Parallel.js初探续集
  • 原文地址:https://www.cnblogs.com/freeneng/p/3098753.html
Copyright © 2011-2022 走看看