代码随想录刷题四十五天
题目思路:
代码实现:
mn = input().split()
n, m = int(mn[0]), int(mn[1])
dp = [0]*(n+1)
dp[0] = 1
for j in range(1, n+1):
for i in range(1, m+1):
if i > j:
dp[j] = dp[j]
else:
dp[j] = dp[j]+dp[j-i]
print(dp[n])
零钱兑换 (LC 322)
题目思路:
代码实现:
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
dp = [float("inf")] * (amount+1)
dp[0] = 0
for i in range(len(coins)):
for j in range(1, amount+1):
if coins[i]<=j:
dp[j] = min(dp[j], dp[j-coins[i]]+1)
if dp[amount] == float("inf"):
return -1
else:
return dp[amount]
完全平方数 (LC 279)
题目思路:
代码实现:
class Solution:
def numSquares(self, n: int) -> int:
target = int(sqrt(n))
dp = [float("inf")] * (n+1)
dp[0] = 0
for i in range(1, target+1):
for j in range(1, n+1):
if i**2<=j:
dp[j] = min(dp[j], dp[j-i**2]+1)
return dp[n]