[leetcode]39. Combination Sum

Given a set of candidate numbers (C) (without duplicates) 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]
]

求所有和为target的可能组合,每个数可以出现多次

思路:DFS,每加入一个值,继续向下遍历别的值,符合条件,加入结果

 1 class Solution(object):
 2     def combinationSum(self, candidates, target):
 3         if not candidates or not target:
 4             return []
 5         res,ress = [],[]
 6         self.dfs(sorted(candidates),target,res,ress)
 7         return ress
 8     
 9     def dfs(self,nums,target,res,ress):
10         if target < 0: return
11         if target==0:
12             ress.append(res)
13         else:
14             for i,v in enumerate(nums):
15                 if v <= target:
16                     self.dfs(nums[i:],target-v,res+[v],ress)
17         return 
原文地址:https://www.cnblogs.com/fcyworld/p/6551470.html