前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[leetcode]39. Combin

[leetcode]39. Combin

作者头像
py3study
发布2020-01-07 11:13:23
2470
发布2020-01-07 11:13:23
举报
文章被收录于专栏:python3

题目:

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] ]

意思说 给你一组正数C,然后 给你一个目标数T, 让你从那组C中找到加在一起等于T的那些组合。 比如 给你7 然后 从[2,3,6,7]中可以找到[2,2,3]和[7]两组组合。 想了一下还是用DFS:

就以这个例子举,比如让我找组成7的数, 首先那个7肯定是。 然后再看,6,如果6在我们结果里,那还得有能组成7-6=1的数,对吧,然而并没有1,放弃6 再看3,如果要有3,那后面要有能组成7-3=4的数, 发现了什么没有。。 只是从需要组成7的变换成需要组成4的,那写一个函数就可以了。

这个函数的主题逻辑是: Target =T,然后从数组中找一个数n,然后在 剩下的部分target 变成了 T-n,以此类推。

函数到哪返回呢,如果目标数T=0,则找的成功,返回,如果目标数T小于C中最小的数,言外之意就是我们找到不这样的组合了,寻找失败,返回。 需要注意的是,答案要求没有重复的,如果只是这么写会变成[2,3,2],[2,2,3],[3,2,2],因此要记下 上一个数,我是从小往大找的,也就是说,

如果我已经找完n=2的情况,再去找n=3的时候,3就不应该往回再选n=2了,只能往后走,不然就会重复。

代码如下:

代码语言:javascript
复制
class Solution(object):
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        self.resList = []
        candidates = sorted(candidates)
        self.dfs(candidates,[],target,0)
        return self.resList
    def dfs(self, candidates, sublist, target, last):
        if target == 0:
            self.resList.append(sublist[:])
        if target< candidates[0]:
            return 
        for n in candidates:
            if n > target:
                return
            if n < last:
                continue
            sublist.append(n)
            self.dfs(candidates,sublist,target - n, n)
            sublist.pop()
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/09/09 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档