Description
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] ]
Constraints:
1 <= candidates.length <= 100
1 <= candidates[i] <= 50
1 <= target <= 30
Explanation
Combinations are subsets of the candidate array. We can use depth-first search to find all combinations of the input array. First, sort candidates array into ascending order.
Second, conduct a depth-first search to visit each combination of the input array.
Java Solution
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> results = new ArrayList<>();
if (candidates == null || candidates.length == 0) {
return results;
}
Arrays.sort(candidates);
List<Integer> combination = new ArrayList<>();
toFindCombinationsToTarget(candidates, results, combination, 0, target);
return results;
}
private void toFindCombinationsToTarget(int[] candidates, List<List<Integer>> results, List<Integer> combination, int startIndex, int target) {
if (target == 0) {
results.add(new ArrayList<>(combination));
return;
}
for (int i = startIndex; i < candidates.length; i++) {
if (i != startIndex && candidates[i] == candidates[i - 1]) {
continue;
}
if (candidates[i] > target) {
break;
}
combination.add(candidates[i]);
toFindCombinationsToTarget(candidates, results, combination, i + 1, target - candidates[i]);
combination.remove(combination.size() - 1);
}
}
}
Python Solution
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
results = []
candidates = sorted(candidates)
self.helper(results, candidates, target, [], 0)
return results
def helper(self, results, candidates, target, combination, start):
if target == 0:
results.append(list(combination))
return
if target < 0:
return
for i in range(start, len(candidates)):
if i != start and candidates[i] == candidates[i - 1]:
continue
combination.append(candidates[i])
self.helper(results, candidates, target - candidates[i], combination, i + 1)
combination.pop()
- Time Complexity: O(2^N)
- Space Complexity: O(N)