Skip to content

Commit ab0c23b

Browse files
[N-0] refactor 77
1 parent 727f2aa commit ab0c23b

File tree

1 file changed

+15
-10
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+15
-10
lines changed

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

+15-10
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@
44
import java.util.ArrayList;
55
import java.util.List;
66

7-
/**Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
7+
/**
8+
* 77. Combinations
9+
*
10+
* Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
811
912
For example,
1013
If n = 4 and k = 2, a solution is:
@@ -16,8 +19,11 @@
1619
[1,2],
1720
[1,3],
1821
[1,4],
19-
]*/
22+
]
23+
*/
24+
2025
public class _77 {
26+
2127
public List<List<Integer>> combine(int n, int k) {
2228
List<List<Integer>> result = new ArrayList();
2329
int[] nums = new int[n];
@@ -28,15 +34,14 @@ public List<List<Integer>> combine(int n, int k) {
2834
return result;
2935
}
3036

31-
void backtracking(int k, int start, int[] nums, List<Integer> temp, List<List<Integer>> result) {
32-
if (temp.size() == k) {
33-
List<Integer> newTemp = new ArrayList(temp);
34-
result.add(newTemp);
35-
} else if (temp.size() < k) {
37+
void backtracking(int k, int start, int[] nums, List<Integer> curr, List<List<Integer>> result) {
38+
if (curr.size() == k) {
39+
result.add(new ArrayList(curr));
40+
} else if (curr.size() < k) {
3641
for (int i = start; i < nums.length; i++) {
37-
temp.add(nums[i]);
38-
backtracking(k, i + 1, nums, temp, result);
39-
temp.remove(temp.size() - 1);
42+
curr.add(nums[i]);
43+
backtracking(k, i + 1, nums, curr, result);
44+
curr.remove(curr.size() - 1);
4045
}
4146
}
4247
}

0 commit comments

Comments
 (0)