题目如下:
Given a set of candidate numbers (candidates
) (without duplicates) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
The same repeated number may be chosen from candidates
unlimited number of times.
Note:
- All numbers (including
target
) will be positive integers. - The solution set must not contain duplicate combinations.
Example 1:
Input: candidates =[2,3,6,7],
target =7
, A solution set is: [ [7], [2,2,3] ] 在此应注意到candidates中的元素可重复出现,且最后的结果中不应包含重复的组合。使用动态规划的想法来解决这个问题:对应每个target,我们可以选择使用candidates中的第一个元素和不使用第一个元素来拼凑,这种想法覆盖了正面与反面,因此递归求解后的组合是不重不漏的。应注意到,使用第一个元素后,target的值应变为target - candidates[0]AC的代码如下:
class Solution(object): def combinationSum(self, candidates, target): if not candidates or target <= 0: return [[], ] res = [] self.combination_help(candidates, [], target, res) return res def combination_help(self, candidates, path, remain, res): if remain < 0 or not candidates: return if remain == 0: res.append(path) return self.combination_help(candidates, path + [candidates[0], ], remain - candidates[0], res) self.combination_help(candidates[1:], path, remain, res)
查看讨论区的方法可以发现,常应用DFS的方法来解决这个问题。其中关键代码如下:
def dfs(self, nums, target, index, path, res): 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)
可以看到,在for循环中,新调用的dfs函数的index参数仍为i, 而非i + 1,这是因为题目中说明每个元素可以使用多次。
而这种for循环的迭代,和上面自己的这种解法实际上是一样的,都是candidates[0]开始不停迭代使用,去凑齐target
原文地址:https://www.cnblogs.com/plank/p/9104160.html
时间: 2024-10-21 05:48:59