LeetCode 39. Combination Sum

来源:互联网 发布:那些大网站用的cn域名 编辑:程序博客网 时间:2024/06/18 05:11

题目:

Given a set of candidate numbers (C) 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]]
题意:

找到可以重复的所有数据集,使得其和为目标值。


题解:

其实就是换零钱问题。

贴一个递归解法。

class Solution(object):    def combinationSum(self, candidates, target):        """        :type candidates: List[int]        :type target: int        :rtype: List[List[int]]        """        res = []        self.dfs(candidates, target, 0, [], res)        return res    def dfs(self, nums, target, index, path, res):         if target < 0: #小于0时,回溯            return        if target == 0:            res.append(path)            return         for i in range(index, len(nums)):            self.dfs(nums, target-nums[i], i, path+[nums[i]], res) 


0 0
原创粉丝点击