|
| 1 | +""" |
| 2 | +Time Complexity: O(n * amount) |
| 3 | +Space Complexity: O(n * amount) |
| 4 | +
|
| 5 | +- DP / Top-Down approach |
| 6 | +- Use a cache to store the results of the subproblems |
| 7 | +""" |
| 8 | +class Solution: |
| 9 | + def coinChange(self, coins: List[int], amount: int) -> int: |
| 10 | + LARGE = 10 ** 5 |
| 11 | + |
| 12 | + @cache |
| 13 | + def dp(coin: int, left: int) -> int: |
| 14 | + if left == 0: |
| 15 | + return 0 |
| 16 | + |
| 17 | + if left < 0 or coin >= len(coins): |
| 18 | + return LARGE |
| 19 | + |
| 20 | + a = dp(coin, left - coins[coin]) + 1 |
| 21 | + b = dp(coin + 1, left) |
| 22 | + |
| 23 | + return min(a, b) |
| 24 | + |
| 25 | + ans = dp(0, amount) |
| 26 | + |
| 27 | + return ans if ans != LARGE else -1 |
| 28 | + |
| 29 | +""" |
| 30 | +Time Complexity: O(n * amount) |
| 31 | +Space Complexity: O(n * amount) |
| 32 | +
|
| 33 | +- DP / Bottom-Up approach |
| 34 | +- Use a 2D array to store the results of the subproblems |
| 35 | +""" |
| 36 | +class Solution: |
| 37 | + def coinChange(self, coins: List[int], amount: int) -> int: |
| 38 | + N = len(coins) |
| 39 | + dp = [[float('inf')] * (amount + 1) for _ in range(N)] |
| 40 | + |
| 41 | + for c in range(N): |
| 42 | + dp[c][0] = 0 |
| 43 | + |
| 44 | + if c > 0: |
| 45 | + for a in range(amount + 1): |
| 46 | + dp[c][a] = dp[c - 1][a] |
| 47 | + |
| 48 | + for a in range(coins[c], amount + 1): |
| 49 | + dp[c][a] = min(dp[c][a], dp[c][a - coins[c]] + 1) |
| 50 | + |
| 51 | + ans = dp[-1][-1] |
| 52 | + |
| 53 | + return ans if ans != float('inf') else -1 |
| 54 | + |
| 55 | +""" |
| 56 | +Time Complexity: O(n * amount) |
| 57 | +Space Complexity: O(amount) |
| 58 | +
|
| 59 | +- DP / Bottom-Up approach [Space Optimized] |
| 60 | +- Use a 1D array to store the results of the subproblems |
| 61 | +""" |
| 62 | +class Solution: |
| 63 | + def coinChange(self, coins: List[int], amount: int) -> int: |
| 64 | + N = len(coins) |
| 65 | + dp = [float("inf")] * (amount + 1) |
| 66 | + dp[0] = 0 |
| 67 | + |
| 68 | + for c in range(N): |
| 69 | + for a in range(coins[c], amount + 1): |
| 70 | + dp[a] = min(dp[a], dp[a - coins[c]] + 1) |
| 71 | + |
| 72 | + return dp[-1] if dp[-1] != float("inf") else -1 |
0 commit comments