|
6 | 6 | public class _77 {
|
7 | 7 |
|
8 | 8 | public static class Solution1 {
|
| 9 | + /** |
| 10 | + * I'm glad that I worked this one out completely on my own on 10/11/2021! Enjoy the beauty of backtracking! |
| 11 | + */ |
9 | 12 | public List<List<Integer>> combine(int n, int k) {
|
10 |
| - List<List<Integer>> result = new ArrayList(); |
11 |
| - int[] nums = new int[n]; |
12 |
| - for (int i = 0; i < n; i++) { |
13 |
| - nums[i] = i + 1; |
| 13 | + List<List<Integer>> ans = new ArrayList<>(); |
| 14 | + for (int num = 1; num <= n - k + 1; num++) { |
| 15 | + List<Integer> list = new ArrayList<>(); |
| 16 | + list.add(num); |
| 17 | + backtracking(list, k - 1, num + 1, n, ans); |
14 | 18 | }
|
15 |
| - backtracking(k, 0, nums, new ArrayList(), result); |
16 |
| - return result; |
| 19 | + return ans; |
17 | 20 | }
|
18 | 21 |
|
19 |
| - void backtracking(int k, int start, int[] nums, List<Integer> curr, List<List<Integer>> result) { |
20 |
| - if (curr.size() == k) { |
21 |
| - result.add(new ArrayList(curr)); |
22 |
| - } else if (curr.size() < k) { |
23 |
| - for (int i = start; i < nums.length; i++) { |
24 |
| - curr.add(nums[i]); |
25 |
| - backtracking(k, i + 1, nums, curr, result); |
26 |
| - curr.remove(curr.size() - 1); |
27 |
| - } |
| 22 | + private void backtracking(List<Integer> list, int k, int start, int limit, List<List<Integer>> ans) { |
| 23 | + if (k == 0) { |
| 24 | + ans.add(new ArrayList<>(list)); |
| 25 | + return; |
| 26 | + } |
| 27 | + for (int num = start; num <= limit; num++) { |
| 28 | + list.add(num); |
| 29 | + backtracking(list, k - 1, num + 1, limit, ans); |
| 30 | + list.remove(list.size() - 1); |
28 | 31 | }
|
29 | 32 | }
|
30 | 33 | }
|
|
0 commit comments