回溯法:
解题思想:
- 这里的关键点是要搞清楚函数的参数应该传什么,这里应该传的是最后结果,要插入的字符串,左括号的个数,右括号的个数和括号对总数n。有了这样的参数,函数处理起来就方便多了,代码也清晰。
- 不满足递归的条件:左括号数或者右括号大于n或者左括号右括号顺序相反;
- 插入res的条件:左右括号数都等于n;
- 最后递归的代码含义是选择左括号或者选择右括号。
C++代码:
class Solution {
public:
/**
* @param n n pairs
* @return All combinations of well-formed parentheses
*/
vector<string> generateParenthesis(int n) {
vector<string> res;
string temp = "";
process(res, temp, 0,0,n);
return res;
}
void process(vector<string>& result, string temp, int left, int right, int n) {
//cout<<temp<<" "<<left<<" "<<right<<endl;
if (left > n || right > n || left < right) {
return;
}
if (left == n && right==n) {
result.push_back(temp);
//cout<<temp<<endl;
return;
}
process(result,temp+"(",left+1,right,n);
process(result,temp+")",left,right+1,n);
}
};