美文网首页
组合相加

组合相加

作者: 水瓶鱼 | 来源:发表于2017-03-26 02:01 被阅读5次

    题目

    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,

    python

    class Solution(object):
        def combinationSum(self, candidates, target):
            """
            :type candidates: List[int]
            :type target: int
            :rtype: List[List[int]]
            """
            result=[]
            candidates.sort();
            self.dfs(candidates,target,0,[],result)
            return result
            
        def dfs(self, nums, target, depth, path, res):
            if target < 0:
                return;
            if target == 0:
                res.append(path)
                return
            for i in range(depth, len(nums)):
                self.dfs(nums, target - nums[i], i, path + [nums[i]], res)
    

    解题思路

    深度优先遍历

    相关文章

      网友评论

          本文标题:组合相加

          本文链接:https://www.haomeiwen.com/subject/phphottx.html