General DP question.
#include <vector>
#include <iostream>
#include <climits>
using namespace std;
/*
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
the amount. If that amount of money cannot be made up by any combination of the coins.
return -1.
Example:
coins = [1, 2, 5], amount = 11
return 3 (11 == 5 + 5 + 1)
coins = [2], amount = 3;
return -1;
*/
int coinChange(vector<int>& coins, int amount) {
vector<int> dp(amount+1, INT_MAX); // this initialize is very important. since some value can't be exchanged.
dp[0] = 0;
for(int i = 1; i <= amount; ++i) {
for(int j = 0; j < coins.size(); ++j) {
if(i - coins[j] >= 0) {
int sub_res = dp[i-coins[j]];
if(sub_res != INT_MAX && sub_res + 1 < dp[i]) dp[i] = sub_res + 1;
}
}
}
if(dp[amount] == INT_MAX) return -1;
return dp[amount];
}
int main(void) {
vector<int> coins{2, 5};
cout << coinChange(coins, 8) << endl;
cout << coinChange(coins, 3) << endl;
}
// Variations.
// Get the total number of coin exchanges to the whole sum.
// number of ways combinations.
// table[i][j] == table[i][j] + table[i][j-coins[k]];
int coinCombinations(int sum, vector<int>& coins) {
int n = coins.size();
vector< vector<int> > table(sum + 1, vector<int>(n, 0));
for(int i = 0; i < n; ++i) {
table[0][i] = 1;
}
for(int i = 1; i <= sum; ++i) {
for(int j = 0; j < n; ++j) {
int x = (i - coins[j] >= 0) ? table[i - coins[j]][j] : 0;
int y = (j >= 1) ? table[i][j-1] : 0;
table[i][j] = x + y;
}
}
return table[sum][n - 1];
}
// To further optimize,
int exchange(vector<int>& coins, int sum) {
vector<int> dp(sum + 1, 0);
dp[0] = 1;
int n = coins.size();
for(int i = 0; i < n; ++i) {
for(int j = coins[i]; j <= sum; ++j) {
dp[j] += dp[j - coins[i]];
}
}
return dp[sum];
}
Another variation:
Given a non-negative number n, find out how many ways n can be made by summing up non-negative integers.
int waysSum(int n) { // these are all backpacking series problems.
vector< vector<int> > dp(n + 1, vector<int>(n + 1, 0));
for(int j = 0; j < n; ++j) {
dp[0][j] = 1;
}
for(int i = 0; i <= n; ++i) {
for(int j = 1; j <= n; ++j) {
// do not include j.
dp[i][j] = dp[i][j-1];
if(i - j >= 0) {
dp[i][j] += dp[i-j][j];
}
}
}
return dp[n][n];
}
int main(void) {
cout << waysSum(2) << endl;
}