您的位置:首页 > 编程语言 > C语言/C++

leetcode #22 in cpp

2016-05-22 04:49 423 查看
The question is to generate all possible combinations of valid parentheses given the number of pair of parentheses. 

Solution: 

We see it is going to get all possible combinations, which reminds us that recurrence is a possible solution.

To solve this, we have to think about what accounts for a valid generation of the valid parentheses. 

Requirement 1:  the number of left parentheses should never less than the one of right parentheses. 

Requirement 2: the number of left parentheses should never more than n, which is given. 

Any violation of these two requirement would generate invalid parentheses.

This leads to a  method of generating a valid parenthesis:

Given a string of valid parenthesis:

if its number of left parentheses is less than n:

if its number of left parentheses is more than the number of right parentheses, we could append 1. one left parentheses to this string;  2. one right
parentheses to this string;

if its number of left parentheses is equal to the number of right parentheses , we could append one left parentheses to this string;

else if its number of left parentheses is equal to n:

We stop appending left parentheses. We append right parentheses until the number of right parentheses reaches n. And then add this string to the final
collection.

Each time after we append a parenthesis, we then pass the new string to the method again.

Code: 

class Solution {
public:
vector<string> generateParenthesis(int n) {

vector<string> res;
if(n == 0) return res;
if(n==1) return vector<string>{"()"};
string s = "";
generate(0,0,n,s, &res);
return res;
}
void generate(int left, int right, int n,string s, vector<string> *res){
if(left == n){
while(right < n){
s+=')';
right ++;
}
res->push_back(s);
}else{
if(left > right){
generate(left, right + 1, n, s+')',res);
}
generate(left + 1, right, n, s+'(',res);
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode cpp