LeetCode Week13

来源:互联网 发布:淘宝上好看的男装 编辑:程序博客网 时间:2024/06/06 15:46
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:

[  "((()))",  "(()())",  "(())()",  "()(())",  "()()()"]
class Solution {public:    vector<string> generateParenthesis(int n) {        vector<string> rs;        string s;        genParenthesis(rs,s,n,n);        return rs;    }        void genParenthesis(vector<string>& rs,string &s,int l,int r)    {        if(l==0)        {            rs.push_back(s);            rs.back().append(r,')');        }        s.push_back('(');        genParenthesis(rs,s,l-1,r);        s.pop_back();        if(l < r)        {               s.push_back(')');            genParenthesis(rs,s,l,r-1);            s.pop_back();        }    }};
class Solution {public:    vector<string> generateParenthesis(int n) {        vector<string> rs;        if(n>0) genParenthesis(rs,"",0,0,n);        return rs;    }    void genParenthesis(vector<string>& rs,string s,int l,int r,int n)    {        if(l == n)        {            rs.push_back(s.append(n-r,')'));            return;                    }        genParenthesis(rs,s+"(",l+1,r,n);        if(l>r) genParenthesis(rs,s+")",l,r+1,n);    }};

class Solution {public:    vector<string> generateParenthesis(int n) {        vector<string> rs;        string s="";        if(n>0) genParenthesis(rs,s,0,0,n);        return rs;    }    void genParenthesis(vector<string>& rs,string s,int l,int r,int n)    {        if(l == n)        {            rs.push_back(s.append(n-r,')'));            return;                    }        s.push_back('(');        genParenthesis(rs,s,l+1,r,n);        s.pop_back();        if(l>r)        {               s.push_back(')');            genParenthesis(rs,s,l,r+1,n);            s.pop_back();        }    }};


原创粉丝点击