mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 07:35:35 +08:00
优化
This commit is contained in:
@ -209,19 +209,19 @@ class Solution:
|
|||||||
def coinChange(self, coins: List[int], amount: int) -> int:
|
def coinChange(self, coins: List[int], amount: int) -> int:
|
||||||
'''版本一'''
|
'''版本一'''
|
||||||
# 初始化
|
# 初始化
|
||||||
dp = [amount + 1]*(amount + 1)
|
dp = [float("inf")]*(amount + 1)
|
||||||
dp[0] = 0
|
dp[0] = 0
|
||||||
# 遍历物品
|
# 遍历物品
|
||||||
for coin in coins:
|
for coin in coins:
|
||||||
# 遍历背包
|
# 遍历背包
|
||||||
for j in range(coin, amount + 1):
|
for j in range(coin, amount + 1):
|
||||||
dp[j] = min(dp[j], dp[j - coin] + 1)
|
dp[j] = min(dp[j], dp[j - coin] + 1)
|
||||||
return dp[amount] if dp[amount] < amount + 1 else -1
|
return dp[amount] if dp[amount] != float("inf") else -1
|
||||||
|
|
||||||
def coinChange1(self, coins: List[int], amount: int) -> int:
|
def coinChange1(self, coins: List[int], amount: int) -> int:
|
||||||
'''版本二'''
|
'''版本二'''
|
||||||
# 初始化
|
# 初始化
|
||||||
dp = [amount + 1]*(amount + 1)
|
dp = [float("inf")]*(amount + 1)
|
||||||
dp[0] = 0
|
dp[0] = 0
|
||||||
# 遍历物品
|
# 遍历物品
|
||||||
for j in range(1, amount + 1):
|
for j in range(1, amount + 1):
|
||||||
@ -229,7 +229,7 @@ class Solution:
|
|||||||
for coin in coins:
|
for coin in coins:
|
||||||
if j >= coin:
|
if j >= coin:
|
||||||
dp[j] = min(dp[j], dp[j - coin] + 1)
|
dp[j] = min(dp[j], dp[j - coin] + 1)
|
||||||
return dp[amount] if dp[amount] < amount + 1 else -1
|
return dp[amount] if dp[amount] != float("inf") else -1
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user