leetcode(19)-组合总和

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取。

说明:

所有数字(包括 target)都是正整数。
解集不能包含重复的组合。 

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

我的解法

数组先排序

先按照共有几个数来搜索,范围是从1,到target.利用最小值进行剪枝。

class Solution:
    def combinationSum(self, candidates, target: int):
        sets = []
        candidates.sort()
        def find(candidates,ans,target, current_depth, max_depth):
            if (max_depth-current_depth)*candidates[0]>target:
                return
            #print(candidates,ans,target,current_depth,max_depth)
            if current_depth==max_depth:
                if target==0:
                    sets.append(ans)
                return
            for j in range(len(candidates)):
                i = candidates[j]
                if i==candidates[j-1] and j-1>=0:
                    continue
                tmp= ans.copy()
                if i<=target:
                    tmp.append(i)                   
                    find(candidates[j:],tmp,target-i,current_depth+1,max_depth)
        for i in range(1,target+1):
            if candidates[0]*i>target:
                break
            find(candidates,[],target,0,i)
        return sets

猜你喜欢

转载自www.cnblogs.com/Lzqayx/p/12157952.html
今日推荐