You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
1.6 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package class28;
import java.util.ArrayList;
import java.util.List;
public class Problem_0022_GenerateParentheses {
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);
}
}
}
// 不剪枝的做法
public static List<String> generateParenthesis2(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;
}
}