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.
- Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
- 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]
Subscribe to see which companies asked this question
详情见注释,两种写法,同一个思路
class Solution(object):
count = 0
'''
def combinationSum(self, candidates, target):
res = []
candidates.sort()
self.dfs(candidates, target, 0, [], res)
return res
def dfs(self, nums, target, index, path, res):
#self.count += 1
#print self.count
if target < 0:
return # backtracking
if target == 0:
res.append(path)
return
for i in xrange(index, len(nums)):
self.dfs(nums, target-nums[i], i, path+[nums[i]], res)
'''
def __init__(self):
self.res = []
def bt(self,c,temp,start,total,target):
#print temp
#self.count += 1
#print self.count
if total == target:
self.res.append(temp)
return
#temp.sort()
#if temp not in self.res:
# self.res.append(temp)
else:
for i in range(start,len(c)):
if total + c[i] <= target:
#temp.append(c[i])#一个是,用append会非常慢,而且必须要用temp[:]指定,否则传值会出现错误
self.bt(c,temp+[c[i]],i,total+c[i],target)
#这里非常重要,这里面的start要改成i,不能每次都从零开始,否则会出现重复
#temp.pop(-1)#可能是,因为,这个不需要往回走,只需要往前看就行了,所以不用pop
def combinationSum(self, candidates, target):
c = candidates
c.sort()
#res = []
#temp = []
self.bt(c,[],0,0,target)
self.res.sort()
#print res
return self.res

本文介绍了一种寻找候选数集合中所有唯一组合的算法,这些组合的和等于目标数。文章提供了详细的Python实现代码,包括递归深度优先搜索(DFS)的使用方法,并强调了去除重复组合的重要性。
413

被折叠的 条评论
为什么被折叠?



