[leetcode]39. Combination Sum,python实现【Medium难度】
2016-06-16 17:01
417 查看
题目:
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了,只能往后走,不然就会重复。
代码如下:
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()
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法