mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-14 01:49:41 +01:00
42 lines
1 KiB
Java
42 lines
1 KiB
Java
|
import java.util.ArrayList;
|
||
|
import java.util.Arrays;
|
||
|
import java.util.HashSet;
|
||
|
import java.util.List;
|
||
|
|
||
|
class Solution {
|
||
|
int[] candidates;
|
||
|
private HashSet<List<Integer>> combinations;
|
||
|
|
||
|
private void combinationSum2(ArrayList<Integer> combination, int target, int i0) {
|
||
|
if (target == 0) {
|
||
|
combinations.add(combination.stream().toList());
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
if (i0 >= candidates.length) {
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
for (int i = i0; i < candidates.length && candidates[i] <= target; ++i) {
|
||
|
if (i > i0 && candidates[i] == candidates[i - 1]) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
combination.addLast(candidates[i]);
|
||
|
combinationSum2(combination, target - candidates[i], i + 1);
|
||
|
combination.removeLast();
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
|
||
|
this.candidates = candidates;
|
||
|
combinations = new HashSet<>();
|
||
|
|
||
|
Arrays.sort(this.candidates);
|
||
|
combinationSum2(new ArrayList<>(), target, 0);
|
||
|
var result = combinations.stream().toList();
|
||
|
|
||
|
return result;
|
||
|
}
|
||
|
}
|