思路:1.注意初始化,dp[1-n]初始化为float('inf')
2.dp[i] = min(dp[j],dp[i-coin[j]] + 1)
class Solution(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
dp = [float('inf')] * (amount + 1)
dp[0] = 0
for i in range(1, amount + 1):
for j in range(len(coins)):
if i - coins[j] >= 0:
dp[i] = min(dp[i], dp[i-coins[j]] + 1)
return -1 if dp[amount] == float('inf') else dp[amount]
题目链接:279. 完全平方数 - 力扣(LeetCode)
思路:跟零钱兑换思路一样
class Solution(object):
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
dp = [float('inf')] * (n + 1)
dp[0] = 0
m = int(math.sqrt(n))
for i in range(1, n + 1):
for j in range(m + 1):
dp[i] = min(dp[i], dp[i - j * j] + 1)
return dp[n]
思路:因为单词的组成有顺序且单词可以重复使用,所以是完全背包问题,且要先遍历背包容量。
这里注意对字符串的处理
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
wordSet = set(wordDict)
n = len(s)
dp = [False] * (n + 1)
dp[0] = True
for i in range(1, n + 1):
for j in range(i):
if dp[j] and s[j:i] in wordSet:#在apple[0:5] 左闭合右开 只到4
dp[i] = True
break
return dp[n]