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;
        }
        
    };
  • 相关阅读:
    24/3=8 睡觉8工作8 8????
    linux上使用redis--宝塔面板
    Ruby--strftime
    JS-页面操作
    JS-确认框
    Rails--bundle exec rake db:migrate
    Jquery--array
    Ruby--hash
    Jquery--string
    Jquery--ajax
  • 原文地址:https://www.cnblogs.com/tonychen-tobeTopCoder/p/5188353.html
Copyright © 2011-2022 走看看