1. 程式人生 > >leetcode python 39. 組合總和(中等,陣列,遞迴)

leetcode python 39. 組合總和(中等,陣列,遞迴)

給定一個無重複元素的陣列 candidates 和一個目標數 target ,找出 candidates 中所有可以使數字和為 target 的組合。
candidates 中的數字可以無限制重複被選取。
說明:所有數字(包括 target)都是正整數。解集不能包含重複的組合。

示例 1:
輸入: candidates = [2,3,6,7], target = 7,
所求解集為:
[
[7],
[2,2,3]
]

思路:
1.target要一次一次不斷的更新,因此需要遞迴
2.結果不要重複,防止出現【2,2,3】和【3,2,2】,所以要給陣列排序,依次向後挑選。
3.挑選時只選擇比過去挑過的大,因為陣列沒有重複值,所以不會出現重複的情況。

class Solution:
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        self.result=[]      #類函式的全域性變數
        candidates=sorted(candidates)   #排序
        self.dummy(candidates,target,[],0)
        return self.result
        
    def dummy(self,candidates,target,s,corr):
        if target==0:
            self.result.append(s[:])
        if target<candidates[0]:
            return
        for i in candidates:     #因為i沒有重複,依次向後走,所以遞迴的結果不會重複
            if i >target:
                return
            if i<corr:
                continue
            s.append(i)
            self.dummy(candidates,target-i,s,i)
            s.pop()
        #具體的遞迴過程要在紙上寫寫

執行用時: 100 ms, 在Combination Sum的Python3提交中擊敗了71.46% 的使用者