class Solution :
def coinChange ( self, coins: List[ int ] , amount: int ) - > int :
size = len ( coins)
dp = [ [ 10 ** 4 + 1 ] * ( amount + 1 ) for _ in range ( size) ]
for i in range ( size) :
dp[ i] [ 0 ] = 0
for m in range ( size) :
for n in range ( 1 , amount + 1 ) :
if coins[ m] <= n:
dp[ m] [ n] = min ( dp[ m - 1 ] [ n] , dp[ m] [ n - coins[ m] ] + 1 )
else :
dp[ m] [ n] = dp[ m - 1 ] [ n]
return - 1 if dp[ - 1 ] [ - 1 ] == 10 ** 4 + 1 else dp[ - 1 ] [ - 1 ]
class Solution:
def numSquares(self, n: int) -> int:
#预处理完全平方数数组
# 题目变成,完全背包中达到目标值的最少元素个数
nums = []
temp = 1
while temp**2 <= n:
nums.append(temp**2)
temp += 1
if nums[-1] == n:
return 1
size = len(nums)
dp = [[10**4 + 1] * (n + 1) for _ in range(size)]
for i in range(size):
dp[i][0] = 0
for i in range(size):
for j in range(1, n + 1):
if nums[i] <= j:
dp[i][j] = min(dp[i - 1][j], dp[i][j - nums[i]] + 1)
else:
dp[i][j] = dp[i - 1][j]
return -1 if dp[-1][-1] == 10**4 + 1 else dp[-1][-1]
class Solution ( object ) :
def wordBreak ( self, s, wordDict) :
wordDict. sort( key= lambda x: len ( x) )
n = len ( s)
dp = [ False ] * ( n + 1 )
dp[ 0 ] = True
for i in range ( 1 , n + 1 ) :
for word in wordDict:
if len ( word) > i:
break
dp[ i] = dp[ i] or ( dp[ i - len ( word) ] and s[ i - len ( word) : i] == word)
return dp[ - 1 ]