LeetCode 22 Generate Parentheses
思路
首先想到动态规划。对于n对括号的情况,可以分解为以下三种:() + n-1对括号,( + n-1对括号 + ),n-1对括号 + ()。但是,“() + n-1对括号”和“n-1对括号 + ()”会有重复。如果增加其他操作去除重复,可能会超时。
考虑其他方式。通过一个变量left记录“还剩多少左括号可以添加”和一个变量right记录“还需要添加多少右括号”。每添加一个左括号,就需要准备一个右括号,因此addParenthesis(rs, s + "(", left - 1, right + 1)。添加一个右括号,只需要right-1,因此addParenthesis(rs, s + ")", left, right - 1)。
代码
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> rs;
addParenthesis(rs, "",n, 0);
return rs;
}
void addParenthesis(vector<string> &rs, string s, int left, int right) {
if (!left && !right) {
rs.push_back(s);
return ;
}
if (left > 0) addParenthesis(rs, s + "(", left - 1, right + 1);
if (right > 0) addParenthesis(rs, s + ")", left, right - 1);
}
};