Skip to content

Commit ad74745

Browse files
add a solution for 77
1 parent 59b6945 commit ad74745

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/main/java/com/fishercoder/solutions/_77.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,31 @@ private void backtracking(List<Integer> list, int k, int start, int limit, List<
3131
}
3232
}
3333
}
34+
35+
public static class Solution2 {
36+
/**
37+
* My completely own solution on 1/24/2022.
38+
*/
39+
public List<List<Integer>> combine(int n, int k) {
40+
List<List<Integer>> ans = new ArrayList<>();
41+
int[] nums = new int[n];
42+
for (int i = 1; i <= n; i++) {
43+
nums[i - 1] = i;
44+
}
45+
backtrack(ans, nums, k, new ArrayList<>(), 0);
46+
return ans;
47+
}
48+
49+
private void backtrack(List<List<Integer>> ans, int[] nums, int k, List<Integer> curr, int start) {
50+
if (curr.size() == k) {
51+
ans.add(new ArrayList<>(curr));
52+
} else if (curr.size() < k) {
53+
for (int i = start; i < nums.length; i++) {
54+
curr.add(nums[i]);
55+
backtrack(ans, nums, k, curr, i + 1);
56+
curr.remove(curr.size() - 1);
57+
}
58+
}
59+
}
60+
}
3461
}

src/test/java/com/fishercoder/_77Test.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,17 @@
77

88
public class _77Test {
99
private static _77.Solution1 solution1;
10+
private static _77.Solution2 solution2;
1011

1112
@BeforeClass
1213
public static void setup() {
1314
solution1 = new _77.Solution1();
15+
solution2 = new _77.Solution2();
1416
}
1517

1618
@Test
1719
public void test1() {
1820
CommonUtils.printListList(solution1.combine(4, 2));
21+
CommonUtils.printListList(solution2.combine(4, 2));
1922
}
2023
}

0 commit comments

Comments
 (0)