(19)leetcode - の組み合わせの和

非反復配列要素の候補と目標数の目標を考えると、あなたはそのターゲット番号との組み合わせのためのすべての候補者を見つけることができます。

候補者の無制限番号が繰り返され、選択することができます。

説明:

(ターゲットを含む)すべての数値は正の整数です。
ソリューションセットは、その重複した組み合わせを含めることはできません。 

出典:滞在ボタン(LeetCode)
リンクhttps://leetcode-cn.com/problems/combination-sum
すべてのネットワークからの控除が著作権を保有。商業転載は、ソースを明記してください許可公式、非商用の転載をご連絡ください。

私の解決策

第一の配列をソートします

探索の合計数の数に応じて、それは1からターゲットまでの範囲である。最小使用剪定します。

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
おすすめ