问题:给定一个无重复的数组candidates和一个目标值target,根据数组中的元素输出和为目标值的所有可能组合,数组中的每个元素可以多次使用,输出结果不能有重复的组合
示例:
输入:candidates = [2,3,6,8] target = 8
输出:[[2,2,2,2],[2,3,3],[2,6],[8]]
解决思路:对candidates进行遍历,相应的减少target,并使用递归的方法,直到target为0,得到和为0的组合
Python代码:
class Solution(object): def combinationSum(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ self.out = [] self.Sum(candidates,target) return self.out def Sum(self,candidates,target,res=[]): if not target: self.out.append(res) return for i in range(len(candidates)): can = candidates[i] if can <= target: self.Sum(candidates[i:],target-can,res+[can]) # To avoid duplicate combinations, input "candidaters[i:] instead of candidates"