#leetcode刷题之路22-括号生成

给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。

例如,给出 n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

 

思路:

 递归:

#include <iostream>
#include <vector>
using namespace std;
void gen(int left,int right,string s,vector<string> &ans)
{
    if(right==0) {ans.push_back(s);    return ;}//右括号用完前,左括号早就用完了。所以返回
    else if(left==right) gen(left-1,right,s+'(',ans);//剩余的左括号数量=右括号数量时,只能放左括号
    else if(left==0) gen(left,right-1,s+')',ans);//左括号都写进s中去了,后面只能写右括号了
    else {gen(left,right-1,s+')',ans);//除上面几种情况外,写左写右均可
        gen(left-1,right,s+'(',ans);
    }
}

vector<string> generateParenthesis(int n) {
    vector<string> ans;
    gen(n,n,"",ans);
    return ans;
}

int main() {
    int n=3;
    vector<string> ans;
    ans=generateParenthesis(n);
    cout<<ans[0]<<endl;
    return 0;
}

 

 

posted @ 2019-03-14 12:21  maitianpt  阅读(142)  评论(0编辑  收藏  举报