题目描述
解题思路
本题难得地方就是该放啥括号,因为要满足括号有效。所以本题简单得做法就是使用剩余的左右括号数量来判断。
如果剩余左括号等于右括号,那么此时只能放左括号,不能放右括号,放了右括号就不合法了。
如果剩余左括号小于右括号,那么此时可以放左括号也可以放右括号
- 如果左括号不为0,那还可以放左括号
如果左括号为0,那左右括号都能放
class Solution {
public List<String> generateParenthesis(int n) {
getParenthesis("", n, n);
return res;
}
List<String> res = new ArrayList<>();
public void getParenthesis(String str, int left, int right) {
if (left == 0 && right == 0) {
res.add(str);
return;
}
// 剩余的 ( 和 ) 相等,那么就只能放左括号
if (left == right) {
getParenthesis(str + "(", left - 1, right);
}
else if (left < right) {
// 剩余的左括号小于右括号,那么即可以放左括号也可以放右括号
if (left > 0) {
getParenthesis(str + "(", left - 1, right);
}
getParenthesis(str + ")", left, right - 1);
}
}
}