组合相加

2017-03-26  本文已影响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)

解题思路

深度优先遍历

上一篇下一篇

猜你喜欢

热点阅读