首页 > 代码库 > Combination Sum

Combination Sum

递归:

class Solution:    # @param candidates, a list of integers    # @param target, integer    # @return a list of lists of integers    def combinationSum(self, candidates, target):        candidates.sort()        if target<candidates[0]:            return []        num_items=len(candidates)        res=[]        for i in range(num_items):            if candidates[i]>target:                break            if candidates[i]==target:                res.append( [candidates[i]] )                break            temp=self.combinationSum(candidates[i:num_items],target-candidates[i])#可以再调用candidates[i],但不能掉用i前面的,会出现重复            for j in temp:                j.append(candidates[i])                j.sort()# ...                res.append(j)        return resif __name__ == __main__:    s=Solution()    print(s.combinationSum([2,3,6,7],7))

 

Combination Sum