Sunday, April 16, 2017

Coin Change problem in C++ using tabulation method dynamic programming

You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
Example 1:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)
Example 2:
coins = [2], amount = 3
return -1.
Note:
You may assume that you have an infinite number of each kind of coin.

class Solution {
public:
    int coinChange(vector<int>& coins, int amount) {
        int n = coins.size();
        vector<vector<int>> v(n+1, vector<int>(amount+1, 0));
        for (int i = 0; i<=n; i++)
            v[i][0] = 0;
        for (int i = 0; i<= amount; i++)
            v[0][i] = INT_MAX;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= amount; j++) {
                if (j>=coins[i-1] && v[i][j-coins[i-1]] < INT_MAX)
                    v[i][j] = min(v[i-1][j], v[i][j-coins[i-1]]+1);
                else
                    v[i][j] = v[i-1][j];
            }
        }
        return (v[n][amount]<INT_MAX)?v[n][amount]:-1;
    }
};

No comments:

Post a Comment