39. Combination Sum
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
ans = []
def backtrack(curr, target):
if target == 0:
ans.append(list(curr))
if target < 0:
return
for candidate in candidates:
if len(curr) > 0:
# 確保只拿比自己大或是相等的數字
if candidate < curr[-1]:
continue
curr.append(candidate)
backtrack(curr, target - candidate)
curr.pop()
backtrack([], target)
return ansLast updated