组合相加

题目

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)

解题思路

深度优先遍历

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,868评论 0 23
  • 最近,我一直在读几本关于性格色彩的书籍,结合之前接触到的工作经验和设计知识,让我对性格色彩对产品的设计影响产生了好...
    曾朋友阅读 1,112评论 2 2
  • 情分多种,各有千秋,友情最暖,亲情最真,爱情最妙。今天就来聊聊爱情。 人都是需要爱与被爱的,但在寻找爱的过程中,通...
    周读札记阅读 347评论 1 3
  • 而周围却干涸似萎 不知是为了炫耀其卑微 还是对比其精神或肉体 折磨 何必就此别过 忘了开始的中心 替谁零落 再次回...
    試可时阅读 218评论 0 0
  • 最近一直在各类财经新闻中看到黄金价格,逻辑大概都是:市场恐慌情绪蔓延,黄金等避险资产价格上升。所以,归结到一点,黄...
    水秋公子阅读 240评论 0 2