public List<String> generateParenthesis(int n){
List<String> result = new ArrayList<>();
String s = "";
addResult(s,n,n,result);
return result;
}
pubic static void addResult(String s ,int left,int right,List<String> res){
if (left == 0 && right == 0) { // 左右括号都不剩余了,递归终止
result.add(s);
return;
}
if (left == right) { //左=右, 先放左
addResult(s + "(", left - 1, right, result);
}
if (left < right) {
if (left > 0) { // 如果左括号还剩余的话,可以拼接左括号
addResult(s + "(", left - 1, right, result);
}
// 如果右括号剩余多于左括号剩余的话,可以拼接右括号
addResult(s + ")", left, right - 1, result);
}
}
leetcode22 有效括号所有组合可能
最新推荐文章于 2024-08-23 15:54:50 发布