广告
返回顶部
首页 > 资讯 > 后端开发 > Python >[leetcode]39. Combin
  • 433
分享到

[leetcode]39. Combin

leetcodeCombin 2023-01-31 05:01:29 433人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

题目: Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the

题目:

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了,只能往后走,不然就会重复。

代码如下:



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()

--结束END--

本文标题: [leetcode]39. Combin

本文链接: https://www.lsjlt.com/news/188906.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作