目录
一、题目描述
数字
n代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。示例 1:
输入:n = 3 输出:["((()))","(()())","(())()","()(())","()()()"]示例 2:
输入:n = 1 输出:["()"]提示:
1 <= n <= 8
二、题目分析
不考虑暴力,因为学不到东西~
2.1 解法一: 回朔算法
【1】如果当前字符串"(" 数量 > ")"的数量时 时,下一个字符可以是 "(" 或 ")",否则下一个字符只能是"("
【2】当"(" 数量 和 ")"的数量都等于n 时,结束,将结果保存下来
在回溯的过程中,所有符合条件的结果就都保存下来了。
2.2 解法二:动态规划
F[1] = ()
那么把新的括号看成最小单元*,F[2] 有3个地方可以插入括号,
第一种 *() 第二种 (*) 第三种()*
可能会有重复,利用集合Set的特性去重即可。
F[2]= ()() / (()) / ()() 去重后 为()() / (())
F(3)= 同理可得
F(n)的问题转为 F(n-1)插入+去重
针对本题,DP解法,时间复杂度跟空间复杂度都高于回溯
三、Java代码
3-1 回溯算法
优化前
class Solution {
public List<String> generateParenthesis(int n) {
// 左括号的数量inLeft
// 右括号的数量inRight
List<String> result=new ArrayList<>();
dg(result,n,0,0,"");
return result;
}
public void dg(List<String> result,int n,int inLeft,int inRight,String str){
if(inLeft==n && inRight==n){
result.add(str);
return;
}
if(inLeft!=n){
dg(result,n,inLeft+1,inRight,str+"(");
}
if(inRight!=n && inRight<inLeft){
dg(result,n,inLeft,inRight+1,str+")");
}
}
}
这样的写法,虽然简明易懂,也不需要对字符串进行回溯操作,但是通过时间是 1ms,只超过了72%的提交。
原因是,String本身是固定长度的,每次进行+运算,都需要转化成StringBuilder再append,那优化的思路就是直接使用StringBuilder即可。
优化后
class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
dg(result, n, 0, 0, new StringBuilder());
return result;
}
public void dg(List<String> result, int n, int inLeft, int inRight, StringBuilder str) {
if (inLeft == n && inRight == n) {
result.add(str.toString());
return;
}
if (inLeft != n) {
dg(result, n, inLeft + 1, inRight, str.append("("));
str.deleteCharAt(str.length() - 1);
}
if (inRight != n && inRight < inLeft) {
dg(result, n, inLeft, inRight + 1, str.append(")"));
str.deleteCharAt(str.length() - 1);
}
}
}
1112



被折叠的 条评论
为什么被折叠?



