You are given an integer array coins
representing coins of different denominations and an integer amount
representing a total amount of money.
Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1
.
You may assume that you have an infinite number of each kind of coin.
Time complexity: O(n x amount)
Space complexity: O(amount)
attention initialization : Since we need to find the minimum value, the initialization we set to infinity float('inf')
AC:
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
dp = [float('inf')] * (amount + 1)
dp[0] = 0
for coin in coins:
for i in range(coin, amount + 1):
dp[i] = min(dp[i], dp[i - coin] + 1)
if dp[amount] == float('inf'):
return -1
else:
return dp[amount]
Given an integer n
, return the least number of perfect square numbers that sum to n
.
A perfect square完全平方数 is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1
, 4
, 9
, and 16
are perfect squares while 3
and 11
are not.
AC but slow:
range(1,1) is the empty set.
class Solution:
def numSquares(self, n: int) -> int:
ls = []
for i in range(1, n + 1):
if self.is_ps(i):
ls.append(i)
dp = [float('inf')] * (n + 1)
dp[0] = 0
for i in range(len(ls)):
for j in range(ls[i], n + 1):
if dp[j - ls[i]] != float('inf'):
dp[j] = min(dp[j], dp[j - ls[i]] + 1)
return dp[n]
def is_ps(self, n):
if math.sqrt(n) == int(math.sqrt(n)):
return True
return False
optimal 1:
class Solution:
def numSquares(self, n: int) -> int:
dp = [float('inf')] * (n + 1)
dp[0] = 0
for i in range(1, n + 1):
if math.sqrt(i) != int(math.sqrt(i)):
continue
for j in range(i, n + 1):
if dp[j - i] != float('inf'):
dp[j] = min(dp[j], dp[j - i] + 1)
return dp[n]
optimal 2: n traverses from largest to smallest
class Solution:
def numSquares(self, n: int) -> int:
dp = [float('inf')] * (n + 1)
dp[0] = 0
for i in range(n, -1, -1):
if math.sqrt(i) != int(math.sqrt(i)): # i**0.5
continue
for j in range(i, n + 1):
if dp[j - i] != float('inf'):
dp[j] = min(dp[j], dp[j - i] + 1)
return dp[n]
best solution:
class Solution:
def numSquares(self, n: int) -> int:
dp = [float('inf')] * (n + 1)
dp[0] = 0
for i in range(1, int(n ** 0.5) + 1): # 遍历物品
for j in range(i * i, n + 1): # 遍历背包
# 更新凑成数字 j 所需的最少完全平方数数量
dp[j] = min(dp[j - i * i] + 1, dp[j])
return dp[n]