-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombinationSum.java
More file actions
35 lines (26 loc) · 1.03 KB
/
CombinationSum.java
File metadata and controls
35 lines (26 loc) · 1.03 KB
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
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<List<Integer>>> sols = new ArrayList<>();
for (int i = 1; i <= target; i++) {
List<List<Integer>> sol = new ArrayList<>();
for(int candidate: candidates) {
int rem = i - candidate;
if (rem < 0) break;
if (rem == 0) {
sol.add(Arrays.asList(candidate));
continue;
}
for (List<Integer> path : sols.get(rem - 1)) {
if (candidate > path.get(0)) continue;
List<Integer> newPath = new ArrayList<>();
newPath.add(candidate);
newPath.addAll(path);
sol.add(newPath);
}
}
sols.add(sol);
}
return sols.get(target - 1);
}
}