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:
“((()))”, “(()())”, “(())()”, “()(())”, “()()()”
题意:
给出括号对数,任意组合,找出所有满足括号匹配原则的字符串。
思路:
考虑出规律即可,规律就是我们要在字符串的任意时刻保证左括号“(”的数目大于右括号的数目“)”即可。^_^
代码:
class Solution {
public:
void addRetStr(int leftNum, int rightNum, string s, vector<string>&ivecs){
if(leftNum == 0 && rightNum == 0){
ivecs.push_back(s);
}
//左括号数目等于右括号数目立即添加左括号来保证规则。
if(leftNum == rightNum){
s += "(";
addRetStr(leftNum-1, rightNum, s, ivecs);
}else{
if(leftNum > 0){
//注意这里参数必须是new string而不能s += "("然后传递参数s,因为还有别的string要用s。
string new_str = s + "(";
addRetStr(leftNum-1, rightNum, new_str, ivecs);
}
if(rightNum > 0){
string new_str = s + ")";
addRetStr(leftNum, rightNum-1, new_str, ivecs);
}
}
}
vector<string> generateParenthesis(int n) {
string s;
vector<string>ret;
addRetStr(n, n, s, ret);
return ret;
}
};
虽然很晚了强迫症还是要写完今天的博客,哈哈
最后 祝自己20岁生日快乐^_^,感谢父母带我来这个世界,感谢我的每一位家人,朋友,加油
life's battle doesn't always go to the stronger or faster man
but sooner or later the man who wins
is the man who thinks he can...