Python版-LeetCode 学习:零钱兑换问题

给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。

说明:你可以认为每种硬币的数量是无限的。
链接:https://leetcode-cn.com/problems/coin-change

多种方法的思考:

方法1:递归

class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        
        def count(n):
            # 基本情况的判定
            if n==0 : return 0
            if n<1 : return -1
            # 初始化
            min_coins=float('INF')
            for coin in coins:
                # 子问题的分解
                subproblem=count(n-coin)
                if subproblem == -1:
                    continue
                # 
                min_coins=min(min_coins,1+subproblem)
            # 如果一直continue,min_coins 不变,就代表没有可以分的可能
            return min_coins if min_coins !=float('INF') else -1

        return count(amount)

方法二: 加入记录表的迭代

class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        
        memo={}
        def count(n):
            # 查找子问题的值
            if n in memo:
                return memo[n]
            if n==0 : return 0
            if n<1 : return -1
            # 初始化
            min_coins=float('INF')
            for coin in coins:
                # 子问题分解
                subproblem=count(n-coin)
                if subproblem == -1:
                    continue
                min_coins=min(min_coins,1+subproblem)
            # 存储子问题的解
            memo[n]= min_coins if min_coins !=float('INF') else -1
            return memo[n]

        return count(amount)

方法三:用list代替dict中间表的迭代

class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        # 初始化结果集
        # 每一个下标对应对应amount,下标对应的最后元素值就是零钱的最小个数
        res=[float('INF')]*(amount+1)
        
        res[0]=0
        for i in range(amount+1):

            for coin in coins:
                # 不可分就下一轮
                if (i-coin) <0: continue
                # 对每一个i进行计算
                res[i]=min(res[i],1+res[i-coin])

        if res[amount] == float('INF'):
            return -1
        else:
            return res[amount]

方法四:利用整除减少循环次数

class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        
        n = len(coins)
        coins.sort(reverse=True)
        self.res = float("inf")
        def dfs(index,target,count):
            coin = coins[index]
            if math.ceil(target/coin)+count>=self.res:
                return
            if target%coin==0:
                self.res = count+target//coin
            if index==n-1:return
            print([range(target//coin,-1,-1)])
            for j in range(target//coin,-1,-1):
                dfs(index+1,target-j*coin,count+j)
        dfs(0,amount,0)

        return int(self.res) if self.res!=float("inf") else -1

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章