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:
parent
dca74915b4
commit
fc92c7a091
1 changed files with 41 additions and 0 deletions
41
java/combination-sum-ii.java
Normal file
41
java/combination-sum-ii.java
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue