39. Combination Sum

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.


def combinationSum(candidates: List[int], target: int):
               
    res = []
    L = len(candidates)
   
    def recurse(prefix, cur, rem):
        if rem == 0:
            res.append(prefix)
            return
       
        for i in range(cur, L):
            candidate = candidates[i]
            timesUsed = 1
            while rem >= candidate * timesUsed:
                recurse(prefix + [candidate] * timesUsed, i + 1, rem-candidate * timesUsed)
                timesUsed += 1
               
               
    candidates.sort()
    recurse([], 0, target)
   
    return res

Comments

Popular posts from this blog

849. Maximize Distance to Closest Person

347. Top K Frequent Elements

139. Word Break