一、刷题:
1.leetcode题目 322. 零钱兑换 - 力扣(LeetCode)(medium)
解决:
- class Solution:
- def coinChange(self, coins: List[int], amount: int) -> int:
- dp = [float('inf')]*(amount + 1)
- dp[0] =0
- for coin in coins:
- for j in range(coin,amount +1):
- dp[j] = min(dp[j],dp[j-coin] +1)
- return dp[amount] if dp[amount]!=float('inf') else -1
2.leetcode题目 279. 完全平方数 - 力扣(LeetCode)(medium)
解决:
- class Solution:
- def numSquares(self, n: int) -> int:
- dp = [float('inf')]*(n+1)
- dp[0] = 0
- for i in range(1,int(math.sqrt(n))+1):
- for j in range(i*i,n+1):
- dp[j] = min(dp[j],dp[j-i*i] +1)
- return dp[n]
3.leetcode题目 . - 力扣(LeetCode)(medium)
解决:
- class Solution:
- def wordBreak(self, s: str, wordDict: List[str]) -> bool:
- ####相当于多重背包中的排列
- dp = [False]*(len(s)+1)
- dp[0] = True
- for i in range(1,len(s)+1):
- for word in wordDict:
- if i >=len(word):
- dp[i] = dp[i] or (dp[i-len(word)] and word == s[(i-len(word)):i])
- return dp[len(s)]