zoukankan      html  css  js  c++  java
  • leetcode 22. 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:

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

    思路一:对于给定的n,有效的括号串长度为2n,我们可以遍历所有的串,如果是有效的,就保存下来。

     1 class Solution {
     2 public:
     3     vector<string> generateParenthesis(int n) {
     4         vector<string> res;
     5         if (n == 0)
     6             return res;
     7         generateParenthesis(0, n, "", res);
     8         return res;
     9     }
    10 private:
    11     void generateParenthesis(int current, const int n, string str, vector<string> &res) {
    12         if (current == 2 * n) {
    13             if (isValid(str))
    14                 res.push_back(str);
    15             return;
    16         }
    17         char c[2] = {'(', ')'};
    18         for (int i = 0; i < 2; i++) { //当前位置有两种选择
    19             generateParenthesis(current + 1, n, str + c[i], res);
    20         }
    21     }
    22     bool isValid(string s) {
    23         int len = s.length();
    24         int distance = 0;
    25         for (int i = 0; i < len; i++) {
    26             if (s[i] == '(') {
    27                 distance++;
    28             } else {
    29                 if (distance <= 0)
    30                     return false;
    31                 distance--;
    32             }
    33         }
    34         return (distance == 0);
    35     }
    36 };

    思路二:对于某个位置,可以放 '(' 的条件是当前'('放的个数小于n,可以放')'的条件是'('的个数大于')

     1 class Solution {
     2 public:
     3     vector<string> generateParenthesis(int n) {
     4         vector<string> res;
     5         if (n == 0)
     6             return res;
     7         generateParenthesis(0, 0, n, "", res);
     8         return res;
     9     }
    10 private:
    11     void generateParenthesis(int open, int close, const int n, string str, vector<string> &res) {
    12         if (str.length() == 2 * n) {
    13             res.push_back(str);
    14             return;
    15         }
    16         if (open < n)
    17             generateParenthesis(open + 1, close, n, str + '(', res);
    18         if (open > close)
    19             generateParenthesis(open, close + 1, n, str + ')', res);
    20     }
    21 };

     符合条件的个数是卡特兰数:

  • 相关阅读:
    python之面向对象之类变量和实例变量
    python之面向对象之封装
    python之shutil模块
    利用python实现冒泡排序
    利用python实现二分法和斐波那契序列
    thinkphp input
    从右向左
    全局修改composer源地址
    Git忽略规则及.gitignore规则不生效的解决办法
    mysql主从数据库不同步的2种解决方法 (转载)
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/11537288.html
Copyright © 2011-2022 走看看