leetcode: 39. Combination Sum

来源:互联网 发布:怎么抓淘宝的数据包 编辑:程序博客网 时间:2024/05/16 13:52

Q

Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.The same repeated number may be chosen from C unlimited number of times.

Note:

All numbers (including target) will be positive integers.The solution set must not contain duplicate combinations.For example, given candidate set [2, 3, 6, 7] and target 7, A solution set is: [  [7],  [2, 2, 3]]

AC

class Solution(object):    def combinationSum(self, candidates, target):        """        :type candidates: List[int]        :type target: int        :rtype: List[List[int]]        """        res = []        candidates.sort()        self.dfs(candidates, target, 0, [], res)        return res    def dfs(self, candidates, target, idx, path, res):        if target < 0:            return        if target == 0:            res.append(path)            return        for i in xrange(idx, len(candidates)):            self.dfs(candidates, target-candidates[i], i, path+[candidates[i]], res)if __name__ == "__main__":    result = Solution().combinationSum([2, 3, 6, 7], 7)    assert result == [[2, 2, 3], [7]]