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

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

    这个问题解的个数为卡特兰数。不过这道题并不是求解的个数,而是将所有合法括号打印出来。

    设leftnum和rightnum为左右括号的剩余量,则leftnum>0时可以继续打印"(",当rightnum>leftnum时可以打印")"。

    class Solution {
    public:
        void generate(int leftnum,int rightnum,string s,vector<string>& res)
        {
            if(leftnum==0 && rightnum==0)
                res.push_back(s);
            if(leftnum>0)
                generate(leftnum-1,rightnum,s+"(",res);
            if(rightnum>leftnum && rightnum>0)
                generate(leftnum,rightnum-1,s+")",res);
        }
        vector<string> generateParenthesis(int n) {
            vector<string> strs;
            generate(n,n,"",strs);
            return strs;
        }
        
    };
  • 相关阅读:
    预定义规则 取范围数据
    oracle table 数组的赋值方法
    java 缓存读写
    webpack
    vscode setting
    webpack babel
    共享你的vscode配置
    github API很丰富
    tips
    todo
  • 原文地址:https://www.cnblogs.com/tonychen-tobeTopCoder/p/5188353.html
Copyright © 2011-2022 走看看