(19) leetcode - the sum of a combination of

Given a non-repeating array element candidates and a target number target, you can find all the candidates for the target numbers and combinations thereof.

Unlimited numbers of candidates may be selected is repeated.

Description:

All figures (including the target) are positive integers.
Solution Set can not contain duplicate combinations thereof. 

Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/combination-sum
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

My solution

Sorting an array of first

According to the number of total number of searches, it ranges from 1 to the target. Minimum use pruning.

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

Guess you like

Origin www.cnblogs.com/Lzqayx/p/12157952.html