|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Recursive function to solve the coin change problem |
| 4 | + int solveRecursive(vector<int>& coins, int x) { |
| 5 | + // Base case: If the remaining amount is 0, no more coins are needed |
| 6 | + if(x == 0) return 0; |
| 7 | + |
| 8 | + // Base case: If the remaining amount is negative, return an invalid result |
| 9 | + if(x < 0) return INT_MAX; |
| 10 | + |
| 11 | + // Initialize the minimum number of coins needed to a large value |
| 12 | + int mini = INT_MAX; |
| 13 | + |
| 14 | + // Iterate over each coin in the list |
| 15 | + for(int i = 0; i < coins.size(); i++) { |
| 16 | + // Recursive call: Try using the current coin and solve for the remaining amount |
| 17 | + int ans = solveRecursive(coins, x - coins[i]); |
| 18 | + |
| 19 | + // If the recursive result is valid, update the minimum number of coins |
| 20 | + if(ans != INT_MAX) |
| 21 | + mini = min(mini, 1 + ans); // Add 1 to include the current coin |
| 22 | + } |
| 23 | + |
| 24 | + // Return the minimum number of coins required to make up the amount x |
| 25 | + return mini; |
| 26 | + } |
| 27 | + |
| 28 | + // Main function to find the minimum number of coins to make up the given amount |
| 29 | + int coinChange(vector<int>& coins, int amount) { |
| 30 | + // Call the recursive function to compute the result |
| 31 | + int ans = solveRecursive(coins, amount); |
| 32 | + |
| 33 | + // If no valid combination of coins is found, return -1 |
| 34 | + if(ans == INT_MAX) return -1; |
| 35 | + |
| 36 | + // Otherwise, return the computed result |
| 37 | + return ans; |
| 38 | + } |
| 39 | +}; |
0 commit comments