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.
N과 M
과 유사한 문제 인거 같음class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
res = []
candidates.sort()
if not candidates or min(candidates) > target:
return []
def dfs(idx, out):
if sum(out) == target:
res.append(out[:])
return
elif sum(out) > target:
return
for i in range(idx, len(candidates)):
out.append(candidates[i])
dfs(i, out)
out.pop()
dfs(0, [])
return res