-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathCombinationSum.java
51 lines (43 loc) · 1.67 KB
/
CombinationSum.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package problems.leetcode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
// https://leetcode.com/problems/combination-sum/
public class CombinationSum {
// runtime: O(2 ^ N) where N is number of candidates
// space: O(N)
public static List<List<Integer>> combinationSum(int[] candidates, int target) {
if (candidates == null || candidates.length < 1) {
return Collections.emptyList();
}
Arrays.sort(candidates);
List<List<Integer>> result = new ArrayList<>();
combinationSum(candidates, target, 0, 0, new ArrayList<>(), result);
return result;
}
private static void combinationSum(int[] candidates, int target, int i, int currentSum, List<Integer> current,
List<List<Integer>> result) {
if (i >= candidates.length) {
return;
}
int candidate = candidates[i];
if (currentSum + candidate == target) {
current.add(candidate);
result.add(new ArrayList<>(current));
current.remove(current.size() - 1);
return;
} else if (currentSum + candidate < target) {
current.add(candidate);
combinationSum(candidates, target, i, currentSum + candidate, current, result);
current.remove(current.size() - 1);
} else {
return;
}
combinationSum(candidates, target, i + 1, currentSum, current, result);
}
public static void main(String[] args) {
System.out.println(combinationSum(new int[] { 2, 3, 6, 7 }, 6));
System.out.println(combinationSum(new int[] { 4, 2, 8 }, 8));
}
}