Combination Sum II
Input:
candidates =
[10,1,2,7,6,1,5]
, target =
8
,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]Analysis
Solution
Last updated
Input:
candidates =
[10,1,2,7,6,1,5]
, target =
8
,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]Last updated
Input:
candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
[1,2,2],
[5]
]class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> ans = new ArrayList<>();
Arrays.sort(candidates);
comboHelper(target, 0, 0, candidates, new ArrayList<Integer>(), ans);
return ans;
}
private void comboHelper(int target, int sum, int startIdx, int[] candidates,
List<Integer> combo, List<List<Integer>> ans) {
if (sum == target) {
ans.add(new ArrayList<Integer>(combo));
return;
}
if (sum > target) {
return;
}
for (int i = startIdx; i < candidates.length; i++) {
combo.add(candidates[i]);
comboHelper(target, sum + candidates[i], i + 1, candidates, combo, ans);
combo.remove(combo.size() - 1);
while (i < candidates.length - 1 && candidates[i + 1] == candidates[i]) {
i++;
}
}
}
}class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> ans = new ArrayList<>();
Arrays.sort(candidates);
comboHelper(target, 0, candidates, new ArrayList<Integer>(), ans);
return ans;
}
private void comboHelper(int remain, int startIdx, int[] candidates,
List<Integer> combo, List<List<Integer>> ans) {
if (remain == 0) {
ans.add(new ArrayList<Integer>(combo));
return;
}
if (remain < 0) {
return;
}
for (int i = startIdx; i < candidates.length; i++) {
combo.add(candidates[i]);
comboHelper(remain - candidates[i], i + 1, candidates, combo, ans);
combo.remove(combo.size() - 1);
while (i < candidates.length - 1 && candidates[i + 1] == candidates[i]) {
i++;
}
}
}
}