Sign in with Google

Google will share your name, email, and profile picture with DevExCode. See our privacy policy.

LeetCode 518: Coin Change II

LeetCode 518 Solution Explanation

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:

  1. Initialize a 1D array dp of size amount + 1 with all values set to 0, except dp[0] = 1.
  2. Iterate through each coin in the coins array.
  3. For each coin, iterate through all amounts from the coin value to the target amount.
  4. 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)

LeetCode 518 Solutions in Java, C++, Python

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];
    }
}

Interactive Code Editor for LeetCode 518

Improve Your LeetCode 518 Solution

Use the editor below to refine the provided solution for LeetCode 518. Select a programming language and try the following:

  • Add import statements 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.

Loading editor...

Related LeetCode Problems