leetcode_ 組合和

typing import List
class Solution:
def combinationSum1(self, candidates: List[int], target: int) -> List[List[int]]:
#必須要排序 最後的結果可能會有順序不一樣但是元素一樣的組合
candidates.sort()
res = []
reslist = []

    def dfs(candidates,target,reslist):
        if target == 0 and reslist not in res:
            res.append(reslist)
            return
        if target<0:
            return

        for i in range(len(candidates)):
            print(reslist)
            #這個遞歸太難,再理解
            dfs(candidates[i+1:],target-candidates[i],reslist+[candidates[i]])

    dfs(candidates,target,reslist)
            function(){ //外匯點差  http://www.kaifx.cn/mt4/kaifx/1749.html
    return res

def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
    candidates.sort()
    # for i in range(candidates):
    res = []
    reslist = []

    def dfs(candidates,begin,target,reslist):
        # for i in range(len(candidates)):
        if target == 0 and reslist not in res:
            res.append(reslist)
            return
        elif target<0 or begin>=len(candidates):
            return
        else:
            # print(reslist,begin)
            dfs(candidates,begin+1,target,reslist)
            dfs(candidates,begin+1,target-candidates[begin],reslist+[candidates[begin]])

    dfs(candidates,0,target,reslist)
    return res

if name == "main":

a = Solution()
print(a.combinationSum1([2,3,6,7],7))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章