题目要求
思路
1.左括号的数量等于右括号的数量等于n作为判出条件,将结果存到res中
2.递归有两种,一种是增加左括号,一种是增加右括号,只要左括号的数量不超过n,就走增加左括号的递归,右括号的数量只要小于左括号的数量,并且右括号的数量少于n,就走增加右括号的逻辑。
代码实现
class Solution {
public:vector<string> generateParenthesis(int n) {vector<string> res;string s;per(0, 0, s, res, n);return res;}void per(int left, int right, string s, vector<string> &res, int n){if(left == n && right == n){res.push_back(s);return;}if(left < n)per(left + 1, right, s + "(", res, n);if(left > right && right < n)per(left, right + 1, s + ")", res, n);}
};