Leetcode#22 Generate Parentheses

来源:互联网 发布:java完全自学手册微盘 编辑:程序博客网 时间:2024/05/16 13:53

Difficulty: Medium

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:

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

方法是递归/回溯,这个很容易想到,但是算法比较难以理清,看完清晰题解之后才理清楚。

具体的方法是通过两个int le 和ri 来记录'('和‘)'的剩余个数,递归赋值,列遍所有可能,算法非常巧妙。

void gen(int le, int ri, string s, vector<string>& ans){    if(le==0&&ri==0)        ans.push_back(s);    if(le>0){        gen(le-1,ri,s+'(',ans);    }    if(ri>le&&ri>0){        gen(le,ri-1,s+')',ans);    }}vector<string> generateParenthesis(int n) {          vector<string> ans;          string s;          gen(n,n,s,ans);          return ans;    }


0 0
原创粉丝点击