forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCombination Sum II.java
40 lines (38 loc) · 1.28 KB
/
Combination Sum II.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
// Runtime: 12 ms (Top 12.41%) | Memory: 43.5 MB (Top 81.01%)
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
// O(nlogn)
Arrays.sort(candidates);
boolean[] visited = new boolean[candidates.length];
helper(res, path, candidates, visited, target, 0);
return res;
}
private void helper(List<List<Integer>> res,
List<Integer> path, int[] candidates,
boolean[] visited, int remain, int currIndex
){
if (remain == 0){
res.add(new ArrayList<>(path));
return;
}
if (remain < 0){
return;
}
for(int i = currIndex; i < candidates.length; i++){
if (visited[i]){
continue;
}
if (i > 0 && candidates[i] == candidates[i - 1] && !visited[i - 1]){
continue;
}
int curr = candidates[i];
path.add(curr);
visited[i] = true;
helper(res, path, candidates, visited, remain - curr, i + 1);
path.remove(path.size() - 1);
visited[i] = false;
}
}
}