Skip to content

Commit c17d2d3

Browse files
committed
提交 括号生成 的代码
1 parent e30cd6b commit c17d2d3

1 file changed

Lines changed: 41 additions & 12 deletions

File tree

‎algorithmCode/src/main/java/weekThree/Number22括号生成.java‎

Lines changed: 41 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,10 @@
1010
*/
1111
public class Number22括号生成 {
1212
public static void main(String[] args) {
13-
recursion(0, 3, "");
13+
// recursion(0, 3, "");
14+
List<String> list = generateParenthesis(3);
15+
System.out.println(list);
16+
1417
}
1518

1619
public static void recursion(int n, int max, String s) {
@@ -24,12 +27,6 @@ public static void recursion(int n, int max, String s) {
2427
System.out.println(s);
2528
}
2629

27-
28-
private static List<String> generateParenthesisValue(int n, ArrayList<String> strings) {
29-
return null;
30-
}
31-
32-
3330
static List<String> res = new ArrayList<>();
3431

3532
public static List<String> generateParenthesis(int n) {
@@ -50,13 +47,45 @@ private static void dfs(int left, int right, String curStr) {
5047
}
5148
}
5249

50+
static class Number22括号生成2 {
51+
public static void main(String[] args) {
52+
List<String> list = generateParenthesis(3);
53+
System.out.println(list.toString());
54+
}
5355

54-
public static int test(int n) {
55-
if (n == 1) {
56-
return 1;
56+
public static List<String> generateParenthesis(int n) {
57+
dfsTest(n, n, "");
58+
return res;
5759
}
58-
return test(n - 1);
59-
}
6060

61+
private static void dfsTest(int left, int right, String s) {
62+
if (left == 0 && right == 0) {
63+
res.add(s);
64+
return;
65+
}
66+
if (left > 0) {
67+
dfsTest(left - 1, right, s + "(");
68+
}
69+
if (left < right) {
70+
dfsTest(left, right - 1, s + ")");
71+
}
72+
}
73+
74+
private static void dfs(int left, int right, String curStr) {
75+
// 左右括号都不剩余了,递归终止
76+
if (left == 0 && right == 0) {
77+
res.add(curStr);
78+
return;
79+
}
80+
if (left > 0) { // 如果左括号还剩余的话,可以拼接左括号
81+
dfs(left - 1, right, curStr + "(");
82+
}
83+
if (right > left) { // 如果右括号剩余多于左括号剩余的话,可以拼接右括号
84+
dfs(left, right - 1, curStr + ")");
85+
}
86+
}
87+
88+
89+
}
6190

6291
}

0 commit comments

Comments
 (0)