1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00

java: add «40. Combination Sum II»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-08-13 14:45:31 +02:00
parent dca74915b4
commit fc92c7a091
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,41 @@
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;
}
}