思路:这道题的解题可以利用回溯的方法,具体过程如图所示一样,首先第一个字符肯定是 “(” ,然后确定回溯的终止条件,什么时候终止一次回溯呢?以N = 3为例,当字符长度为2*N的时候也就是6的时候,就是一次回溯的终止条件了,因为意味着,括号都添加完了,所以这个时候就需要把此时的字符串放进答案组中了。这里可以取两个方向,left、right,分别代表着字符串中添加“(”和“)”。
具体代码:
class Solution {
public:
vector<string> result;
string current;
void backtracking(int n, int left, int right, string& cur,vector<string>& result) {
if (cur.length() == n*2)
{
result.push_back(cur);
return ;
}
if (left < n) {
cur.push_back('(');
backtracking(n, left + 1, right, cur, result);
cur.pop_back();
}
if (right < left) {
cur.push_back(')');
backtracking(n, left, right + 1, cur, result);
cur.pop_back();
}
}
vector<string> generateParenthesis(int n) {
//backtracking();
backtracking(n, 0, 0, current, result);
return result;
}
};