-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
36 lines (33 loc) · 1.1 KB
/
Copy pathSolution.java
File metadata and controls
36 lines (33 loc) · 1.1 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
36
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class Solution {
//Time Complexity: O(n*target)
//Space Complexity: O(target)
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
if (candidates == null || candidates.length == 0) {
return res;
}
Arrays.sort(candidates);
backtrack(res, candidates, 0, target, new ArrayList<>());
return res;
}
private void backtrack(List<List<Integer>> res, int[] candidates, int index, int target, List<Integer> temp){
if (target < 0) {
return;
}
if (target == 0) {
res.add(new ArrayList<>(temp));
return;
}
for (int i = index; i < candidates.length; i++) {
if (i > index && candidates[i] == candidates[i - 1]) {
continue;
}
temp.add(candidates[i]);
backtrack(res, candidates, i + 1, target - candidates[i], temp);
temp.remove(temp.size() - 1);
}
}
}