AlgoMaster Logo

Coin Change II

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

Approach 1: Recursion

Intuition:

Use recursion to explore all possible ways to make up the amount using combinations of the coins. The idea is to traverse each coin and either take it (reduce the amount) or skip it and move to the next coin. This basic approach generates all combinations but is not efficient due to repeated computations.

Code:

2. Dynamic Programming - 2D Array

Intuition:

To avoid the repetition in the recursive approach, use a 2D DP table. Here, dp[i][j] represents the number of ways to get the amount j using first i coin types. The table is filled in a bottom-up manner.

Code:

3. Dynamic Programming - 1D Array

Intuition:

Further optimize the space usage by using a 1D DP array. Instead of maintaining a 2D array, keep track of number of ways to achieve different sums using a single 1D DP array. Here, dp[j] represents the number of ways to get the amount j.

Code: