518. Coin Change II
Explanation
To solve this problem, we can use dynamic programming. We will create a 1D array dp
where dp[i]
represents the number of combinations to make up amount i
. We initialize dp[0]
as 1, since there is one way to make up amount 0, which is by using no coins. Then, for each coin, we iterate through all amounts from the coin value to the target amount and update the number of combinations accordingly.
Algorithm:
- Initialize a 1D array
dp
of sizeamount + 1
with all values set to 0, exceptdp[0] = 1
. - Iterate through each coin in the
coins
array. - For each coin, iterate through all amounts from the coin value to the target amount.
- Update
dp[j] = dp[j] + dp[j - coin]
to accumulate the number of combinations.
Time Complexity: O(amount * n), where n is the number of coins Space Complexity: O(amount)
class Solution {
public int change(int amount, int[] coins) {
int[] dp = new int[amount + 1];
dp[0] = 1;
for (int coin : coins) {
for (int j = coin; j <= amount; j++) {
dp[j] += dp[j - coin];
}
}
return dp[amount];
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.