1. 程式人生 > >[leetcode]39. Combination Sum,python實現【Medium難度】

[leetcode]39. Combination Sum,python實現【Medium難度】

題目:

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:
[
[7],
[2, 2, 3]
]

意思說 給你一組正數C,然後 給你一個目標數T, 讓你從那組C中找到加在一起等於T的那些組合。
比如 給你7 然後 從[2,3,6,7]中可以找到[2,2,3]和[7]兩組組合。
想了一下還是用DFS:

就以這個例子舉,比如讓我找組成7的數
首先那個7肯定是。
然後再看,6,如果6在我們結果裡,那還得有能組成7-6=1的數,對吧,然而並沒有1,放棄6
再看3,如果要有3,那後面要有能組成7-3=4的數,
發現了什麼沒有。。
只是從需要組成7的變換成需要組成4的,那寫一個函式就可以了。

這個函式的主題邏輯是:
Target =T,然後從陣列中找一個數n,然後在 剩下的部分target 變成了 T-n,以此類推。

函式到哪返回呢,如果目標數T=0,則找的成功,返回,如果目標數T小於C中最小的數,言外之意就是我們找到不這樣的組合了,尋找失敗,返回。
需要注意的是,答案要求沒有重複的,如果只是這麼寫會變成[2,3,2],[2,2,3],[3,2,2],因此要記下 上一個數,我是從小往大找的,也就是說,

如果我已經找完n=2的情況,再去找n=3的時候,3就不應該往回再選n=2了,只能往後走,不然就會重複。

程式碼如下:



class Solution(object):
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
self.resList = [] candidates = sorted(candidates) self.dfs(candidates,[],target,0) return self.resList def dfs(self, candidates, sublist, target, last): if target == 0: self.resList.append(sublist[:]) if target< candidates[0]: return for n in candidates: if n > target: return if n < last: continue sublist.append(n) self.dfs(candidates,sublist,target - n, n) sublist.pop()