代码随想录算法训练营第45天| 70. 爬楼梯、322. 零钱兑换、279.完全平方数

70. 爬楼梯:


代码思路

class Solution:
    def climbStairs(self, n: int) -> int:
        if n <= 2:
            return n
        dp = [-1 for i in range(n+1)]
        dp[1] = 1
        dp[2] = 2
        i = 3
        while i <= n:
            dp[i] = dp[i-1] + dp[i - 2]
            i += 1
        return dp[n]

322. 零钱兑换:


代码思路

class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        dp = [float('inf')] * (amount + 1)
        dp[0] = 0
        
        for coin in coins:
            for x in range(coin, amount + 1):
                dp[x] = min(dp[x], dp[x - coin] + 1)
        return dp[amount] if dp[amount] != float('inf') else -1 

279.完全平方数:


代码思路

class Solution:
    def numSquares(self, n: int) -> int:
        dp=[i for i in range(n+1)]
        for i in range(2,n+1):
            for j in range(1,int(i**(0.5))+1):
                dp[i]=min(dp[i],dp[i-j*j]+1)
        return dp[-1]

你可能感兴趣的:(代码随想录打卡,算法,leetcode,动态规划)