322. Coin Change 279. Perfect Squares

文章介绍了使用动态规划方法解决两个问题:给定硬币面额数组,找到组成指定金额所需的最少硬币数;以及计算使总和等于给定整数n的最少完美平方数。两种问题都涉及从大到小或从小到大遍历并更新状态数组来找到最优解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

322. Coin Change

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

You may assume that you have an infinite number of each kind of coin.

 Time complexity: O(n x amount)

Space complexity: O(amount)

attention  initialization  : Since we need to find the minimum value, the initialization we set to infinity  float('inf')

AC:

class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        dp = [float('inf')] * (amount + 1)
        dp[0] = 0

        for coin in coins:
            for i in range(coin, amount + 1):        
               dp[i] = min(dp[i], dp[i - coin] + 1)

        if dp[amount] == float('inf'):
            return -1
        else:
            return dp[amount]

279. Perfect Squares

Given an integer n, return the least number of perfect square numbers that sum to n.

perfect square完全平方数  is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 149, and 16 are perfect squares while 3 and 11 are not.

 AC  but slow: 

range(1,1) is the empty set.

class Solution:
    def numSquares(self, n: int) -> int:
        ls = []
        for i in range(1, n + 1):
            if self.is_ps(i):
                ls.append(i)
        
        dp = [float('inf')] * (n + 1)
        dp[0] = 0

        for i in range(len(ls)):
            for j in range(ls[i], n + 1):
                if dp[j - ls[i]] != float('inf'):
                    dp[j] = min(dp[j], dp[j - ls[i]] + 1)    
        return dp[n]

    
    def is_ps(self, n):
        if math.sqrt(n) == int(math.sqrt(n)):
            return True
        return False

 optimal 1:

class Solution:
    def numSquares(self, n: int) -> int:    
        dp = [float('inf')] * (n + 1)
        dp[0] = 0

        for i in range(1, n + 1):
            if math.sqrt(i) != int(math.sqrt(i)):
                    continue
            for j in range(i, n + 1):    
                if dp[j - i] != float('inf'):
                    dp[j] = min(dp[j], dp[j - i] + 1)    
        return dp[n]

optimal 2: n traverses from largest to smallest

class Solution:
    def numSquares(self, n: int) -> int:    
        dp = [float('inf')] * (n + 1)
        dp[0] = 0

        for i in range(n, -1, -1):
            if math.sqrt(i) != int(math.sqrt(i)): # i**0.5
                    continue
            for j in range(i, n + 1):    
                if dp[j - i] != float('inf'):
                    dp[j] = min(dp[j], dp[j - i] + 1)  
                      
        return dp[n]

best solution:

class Solution:
    def numSquares(self, n: int) -> int:
        dp = [float('inf')] * (n + 1)
        dp[0] = 0

        for i in range(1, int(n ** 0.5) + 1):  # 遍历物品
            for j in range(i * i, n + 1):  # 遍历背包
                # 更新凑成数字 j 所需的最少完全平方数数量
                dp[j] = min(dp[j - i * i] + 1, dp[j])

        return dp[n]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值