Given an array 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:
target
) will be positive integers.Input: candidates = [10,1,2,7,6,1,5], target = 8
Output: [[1,1,6],[1,2,5],[1,7],[2,6]]
Input: candidates = [2,5,2,1,2], target = 5
Output: [[1,2,2],[5]]
Can the candidates array contain negative numbers? No, all numbers are positive integers.
Can the target number be zero? No, the target number will always be a positive integer.
Is the order of combinations in the output important? No, the order of combinations in the output is not important.
Can the candidates array contain duplicates? Yes, the array can contain duplicates, but the combinations must be unique.
def combinationSum2(candidates, target):
def backtrack(start, end, temp_list, target):
if target == 0:
res.append(temp_list[:])
return
if target < 0:
return
for i in range(start, end):
if i > start and candidates[i] == candidates[i - 1]:
continue
temp_list.append(candidates[i])
backtrack(i + 1, end, temp_list, target - candidates[i])
temp_list.pop()
candidates.sort()
res = []
backtrack(0, len(candidates), [], target)
return res
# Example Usage
candidates = [10, 1, 2, 7, 6, 1, 5]
target = 8
print(combinationSum2(candidates, target)) # Output: [[1,1,6], [1,2,5], [1,7], [2,6]]
The overall time complexity is difficult to determine exactly due to the variable nature of backtracking, but we can provide an estimate:
Thus, the total estimated time complexity is (O(n \log n + 2^n)).
This time complexity can vary significantly based on the input size and the values of the target and candidates array.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?