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 };

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

  • 相关阅读:
    找出互联网符合的产品实例
    以软件周期来说明不同的测试的使用情况
    scrapy多个page爬取, post请求, 通过爬到的URL继续发请求爬页面
    Scrapy 安装, 基础使用, 持久化存储
    Linux nginx+uWSGI+django+virtualenv+supervisor发布web服务器
    Linux Nginx
    Linux virtualenv, virtualenvwrapper, pip freeze
    Linux Python安装
    Redis, Python操作Redis, Linux操作Redis, Redis命令, Redis发布订阅, Redis持久化, Redis主从同步
    爬虫 selenium
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/11537288.html
Copyright © 2011-2022 走看看