Combination Sum II LeetCode
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.
Each number in candidates may only be used once in the combination.
Note: The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [10,1,2,7,6,1,5], target = 8
Output:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
Example 2:
Input: candidates = [2,5,2,1,2], target = 5
Output:
[
[1,2,2],
[5]
]
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(candidates);
backtrack(candidates, 0, target, new ArrayList<>(), result);
return result;
}
private void backtrack(int[] candidates, int start, int target, List<Integer> path, List<List<Integer>> result) {
// Base case: target exactly zero
if (target == 0) {
result.add(new ArrayList<>(path)); // Add a copy of the current path
return;
}
// Base case: target becomes negative (invalid path)
if (target < 0) {
return;
}
// Explore further by trying all candidates starting from 'start' index
for (int i = start; i < candidates.length; i++) {
if(i > start && candidates[i]==candidates[i-1]) continue;
path.add(candidates[i]); // Choose
backtrack(candidates, i+1, target - candidates[i], path, result); // Not i+1 because reuse allowed
path.remove(path.size() - 1); // Backtrack
}
}
}
Comments
Post a Comment