- categories: Code, Interview Question, leetcode, Medium
- source: https://leetcode.com/problems/combination-sum
- topics: Backtracking
Given an array of distinct integers candidates
and a target integer target
, return a list of all unique combinations of candidates
where the chosen numbers sum to target
. You may return the combinations in any order.
The same number may be chosen from candidates
an unlimited number of times. Two combinations are unique if the
frequency
of at least one of the chosen numbers is different.
The test cases are generated such that the number of unique combinations that sum up to target
is less than 150
combinations for the given input.
Backtracking + Sort
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
def backtrack(curr, n, curr_target):
for i in range(n, len(candidates)):
if candidates[i] == curr_target:
ans.append(curr + [candidates[i]])
elif candidates[i] < curr_target:
curr.append(candidates[i])
backtrack(curr, n, curr_target - candidates[i])
curr.pop()
n += 1
candidates.sort()
ans = []
backtrack([], 0, target)
return ans