letcode-括号生成
递归大法,空间换时间
就是记录左右括号数,一旦右括号数大于左括号数,退出。
当左右括号数相等,且等于n则为合法解。
- 使用char数组取代StringBuilder可以减少内存使用,这样每次进行回溯时不需要再去删除末尾一位。
class Solution {
/**
* 括号生成
* */
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
char[] temp = new char[n * 2];
/**
* L-左括号数
* R-右括号数
* L + R = temp 下标
* */
temp[0] = '(';
deepParenthesis(result, temp, n, 1, 0);
return result;
}
private void deepParenthesis(List<String> result, char[] temp, int n, int L, int R){
if (L==R && L ==n){
/** 左右括号数相等,且等于给定括号数 */
result.add(String.valueOf(temp));
return;
}
/** 左括号数小等于n,且不小于右括号数 */
if (L <= n && L >= R){
/** 下一步左括号 */
temp[L + R] = '(';
deepParenthesis(result, temp,n, L + 1, R);
/** 下一步右括号 */
temp[L + R] = ')';
deepParenthesis(result, temp,n, L, R + 1);
}
}
}
本文作者:bokerr
本文链接:https://www.cnblogs.com/bokers/p/15575200.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步