Skip to content

Commit f9e8d55

Browse files
authored
Create 02 - Top-Down | DP | Approach.cpp
1 parent 58724e4 commit f9e8d55

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
class Solution {
2+
public:
3+
// Helper function to solve the coin change problem using recursion with memoization
4+
int solve(vector<int>& coins, int x, vector<int>& dp) {
5+
// Base case: If the target amount is 0, no coins are needed
6+
if(x == 0) return 0;
7+
8+
// Base case: If the target amount is negative, return an invalid result
9+
if(x < 0) return INT_MAX;
10+
11+
// If the result for the current amount is already computed, return it
12+
if(dp[x] != -1) return dp[x];
13+
14+
// Initialize the minimum number of coins required to a large value
15+
int mini = INT_MAX;
16+
17+
// Iterate through each coin
18+
for(int i = 0; i < coins.size(); i++) {
19+
// Recursive call: Try using the current coin and solve for the remaining amount
20+
int ans = solve(coins, x - coins[i], dp);
21+
22+
// If the recursive result is valid, update the minimum number of coins
23+
if(ans != INT_MAX)
24+
mini = min(mini, 1 + ans); // Add 1 to include the current coin
25+
}
26+
27+
// Store the computed result in the memoization array
28+
dp[x] = mini;
29+
30+
// Return the computed result
31+
return mini;
32+
}
33+
34+
// Main function to find the minimum number of coins needed to make up the given amount
35+
int coinChange(vector<int>& coins, int amount) {
36+
// Create a memoization array initialized with -1
37+
vector<int> dp(amount + 1, -1);
38+
39+
// Call the recursive helper function with memoization
40+
int ans = solve(coins, amount, dp);
41+
42+
// If no valid combination of coins can form the amount, return -1
43+
if(ans == INT_MAX) return -1;
44+
45+
// Otherwise, return the computed result
46+
return ans;
47+
}
48+
};

0 commit comments

Comments
 (0)