题目

别逼逼,先看代码
class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
// 回溯
String current = "";
dfs(current,n * 2, -1,0,result);
return result;
}
private void dfs(String cur,int maxLength ,int index,int left , List<String> result){
if (left < 0 || left * 2 > maxLength || maxLength - (index + 1) < left){
// left < 0 ,代表右括号比左括号多,后面补左也没用了
// maxLength - left > index 超过一半了左括号,也不合法
return;
}
if (index + 1 == maxLength){
result.add(cur);
return;
}
cur = cur + "(";
dfs(cur,maxLength,index + 1, left + 1 ,result);
cur = cur.substring(0,cur.length() -1 );
cur = cur + ")";
dfs(cur,maxLength,index + 1, left - 1 ,result);
}
}
我的解题思路
- 这道题看起来,就是不断尝试,如果给一个左括号,那么就必须有一个右括号对应。每次判断是否左括号都有右括号成本挺高的。
- 换个思路,如果记录了左括号的数量,如果左括号的数量超过一半,那就代表没有足够位置放右括号。【left * 2 > maxLength】
- 或者,如果剩余的长度,不足让所有的左括号都配置右括号,就认为失败。【maxLength - (index + 1) < left】
- 或者全是右括号【left < 0】
- 既然是不断尝试的,比较合适算法就是回溯了,尝试,回退嘛