Skip to content

Commit d0ae983

Browse files
MEDIUM/src/medium/CombinationSumIII.java
1 parent d8448f0 commit d0ae983

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package medium;
2+
3+
import java.util.*;
4+
5+
public class CombinationSumIII {
6+
public List<List<Integer>> combinationSum3(int k, int n) {
7+
List<List<Integer>> result = new ArrayList();
8+
int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
9+
helper(k, n, nums, 0, new ArrayList(), result);
10+
return result;
11+
}
12+
13+
void helper(int k, int n, int[] nums, int start, List<Integer> curr, List<List<Integer>> result) {
14+
if (n > 0) {
15+
for (int i = start; i < nums.length; i++) {
16+
curr.add(nums[i]);
17+
helper(k, n - nums[i], nums, i + 1, curr, result);// it needs to be a unique set of
18+
// numbers, so we need to set it
19+
// as i+1 here: each number is
20+
// used only once in this array:
21+
// [1,2,3,4,5,6,7,8,9]
22+
curr.remove(curr.size() - 1);
23+
}
24+
} else if (n == 0 && curr.size() == k) {//this is the major difference here: check size of curr list is of k before adding it
25+
List<Integer> temp = new ArrayList(curr);
26+
result.add(temp);
27+
}
28+
}
29+
}

0 commit comments

Comments
 (0)