leetcode刷题记录
题目 括号生成
题目描述
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例 1:
输入:n = 3
输出:[“((()))”,“(()())”,“(())()”,“()(())”,“()()()”]
示例 2:
输入:n = 1
输出:[“()”]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/generate-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
本题主要锻炼剪枝的能力
怎么剪枝
在做分枝的时候, 不合法的提前杀死
如果你要合法,在任意的前缀上,左括号数量不能少于右括号数量
代码
不减枝
public static List<String> generateParenthesis(int n) {
char[] path = new char[n << 1];
List<String> ans = new ArrayList<>();
process2(path, 0, ans);
return ans;
}
public static void process2(char[] path, int index, List<String> ans) {
if (index == path.length) {
if (isValid(path)) {
ans.add(String.valueOf(path));
}
} else {
path[index] = '(';
process2(path, index + 1, ans);
path[index] = ')';
process2(path, index + 1, ans);
}
}
public static boolean isValid(char[] path) {
int count = 0;
for (char cha : path) {
if (cha == '(') {
count++;
} else {
count--;
}
if (count < 0) {
return false;
}
}
return count == 0;
}
letcode时间打败 25%的人
减枝
public static List<String> generateParenthesis(int n) {
char[] path = new char[n << 1];
List<String> ans = new ArrayList<>();
process(path, 0, 0, n, ans);
return ans;
}
// path 做的决定 path[0....index-1]做完决定的!
// path[index.....] 还没做决定,当前轮到index位置做决定!
public static void process(char[] path, int index, int leftMinusRight, int leftRest, List<String> ans) {
if (index == path.length) {
ans.add(String.valueOf(path));
} else {
// index ( )
if (leftRest > 0) {
path[index] = '(';
process(path, index + 1, leftMinusRight + 1, leftRest - 1, ans);
}
if (leftMinusRight > 0) {
path[index] = ')';
process(path, index + 1, leftMinusRight - 1, leftRest, ans);
}
}
}
letcode时间打败 100%的人,可以看出提升还是非常大的