Coin Change II
LeetCode 518 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
ways[i][a] = ways[i-1][a] + ways[i][a − coin].
ನಾನು Coin Change II (LeetCode 518) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Unbounded Knapsack ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Now we count combinations instead of minimising coins. Process coins one at a time so that each combination is counted once in a fixed coin order: for each coin, either never use it again or use it once more and stay on it.
Approach
- 1
Row 0: an amount is reachable in exactly one way if it's a multiple of coins[0].
- 2
For each later coin, exclude it (row above) plus include it (same row, smaller amount).
- 3
Amount 0 always has one way: take nothing.
- 4
Answer is the last cell.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ · ಮೊದಲ ಆಲೋಚನೆಯಿಂದ ಅಂತಿಮ ಪರಿಹಾರದವರೆಗೆ
Count with lru_cache dfs(index, target).
2-D count table.
Recursion + memoPythonO(n·amount) time
from functools import lru_cache
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
#unbounded knapsack
@lru_cache(maxsize=None)
def dfs(index, cur_target):
if cur_target==0:
return 1
if index<0:
return 0
exclude = dfs(index-1,cur_target)
include = 0
if coins[index]<=cur_target:
include=dfs(index, cur_target-coins[index])
return include+exclude
return dfs(len(coins)-1,amount)TabulationPythonO(n·amount) time · O(n·amount) space
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
#unbounded knapsack
n = len(coins)
dp = [[0]*(amount+1) for _ in range(n)]
for a in range(amount+1):
if a%coins[0]==0:
dp[0][a]=1
for index in range(1,n):
for cur_target in range(amount+1):
exclude = dp[index-1][cur_target]
include = 0
if coins[index]<=cur_target:
include=dp[index][cur_target-coins[index]]
dp[index][cur_target]=include+exclude
return dp[n-1][amount]Coin Change II — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Coin Change II ಹಿಂದಿನ intuition ಏನು?
Now we count combinations instead of minimising coins. Process coins one at a time so that each combination is counted once in a fixed coin order: for each coin, either never use it again or use it once more and stay on it.
Coin Change II (LeetCode 518) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Row 0: an amount is reachable in exactly one way if it's a multiple of coins[0]. 2. For each later coin, exclude it (row above) plus include it (same row, smaller amount). 3. Amount 0 always has one way: take nothing. 4. Answer is the last cell.
Coin Change II ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(n · amount). Space: O(n · amount). (Accepted approach: Tabulation.)
Coin Change II ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Looping amounts outer and coins inner counts permutations, not combinations.
Coin Change II ಅನ್ನು ಪರಿಹರಿಸಲು ಒಂದಕ್ಕಿಂತ ಹೆಚ್ಚು ಮಾರ್ಗಗಳಿವೆಯೇ?
Recursion + memo (O(n·amount) time): Count with lru_cache dfs(index, target). Tabulation (O(n·amount) time · O(n·amount) space): 2-D count table.