mirror of
https://github.com/prdlk/leetcode.git
synced 2026-11-02 21:22:43 +00:00
chore: clean up content phase organization
This commit is contained in:
1 parent
5dc2265ee5
commit
6f9e4ecb3b
14 files changed
+706
-45
No files matched your search
@@ -0,0 +1,72 @@
|
||||
"""
|
||||
322. Coin Change
|
||||
Difficulty: Medium
|
||||
https://leetcode.com/problems/coin-change/
|
||||
|
||||
──────────────────────────────────────────────────
|
||||
|
||||
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.
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: coins = [1,2,5], amount = 11
|
||||
Output: 3
|
||||
Explanation: 11 = 5 + 5 + 1
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: coins = [2], amount = 3
|
||||
Output: -1
|
||||
|
||||
Example 3:
|
||||
|
||||
Input: coins = [1], amount = 0
|
||||
Output: 0
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
• 1 <= coins.length <= 12
|
||||
|
||||
• 1 <= coins[i] <= 2^31 - 1
|
||||
|
||||
• 0 <= amount <= 10^4
|
||||
"""
|
||||
|
||||
from math import inf
|
||||
|
||||
|
||||
class Solution:
|
||||
def coinChange(self, coins: list[int], amount: int) -> int:
|
||||
n = len(coins)
|
||||
memo = [[-1] * (amount + 1) for _ in range(n + 1)]
|
||||
|
||||
def min_coins(coins, i, amount, memo):
|
||||
if amount == 0:
|
||||
return 0
|
||||
if i == 0 or amount < 0:
|
||||
return inf
|
||||
if memo[i][amount] != -1:
|
||||
return memo[i][amount]
|
||||
|
||||
skip = min_coins(coins, i - 1, amount, memo)
|
||||
use = min_coins(coins, i, amount - coins[i - 1], memo)
|
||||
if use != inf:
|
||||
use += 1
|
||||
|
||||
memo[i][amount] = min(skip, use)
|
||||
return memo[i][amount]
|
||||
|
||||
result = min_coins(coins, n, amount, memo)
|
||||
return result if result != inf else -1 # pyright: ignore[reportReturnType]
|
||||
Reference in new issue
Block a user