Skip to content

Instantly share code, notes, and snippets.

@Arieg419
Created December 27, 2016 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Arieg419/8593cb1802d27fab5219c1fd26e3f5e2 to your computer and use it in GitHub Desktop.
Save Arieg419/8593cb1802d27fab5219c1fd26e3f5e2 to your computer and use it in GitHub Desktop.
function waysToReturnMemoize(amount, denominations) {
// intialize an array of zeros with indices up to amount
var waysOfDoingNcents = [];
for (var i = 0; i <= amount; i++) {
waysOfDoingNcents[i] = 0;
}
// there is 1 way to renturn 0 cents
waysOfDoingNcents[0] = 1;
for (var j = 0; j < denominations.length; j++) {
// we can only start returning change with coins in our denominations
var coin = denominations[j];
// we start bottom up, each time reducing change amout with curr coin.
for (var higherAmount = coin; higherAmount <= amount; higherAmount++) {
var higherAmountRemainder = higherAmount - coin;
// ways to create change is equivalent to reducing the problem to a known problem
// and gaining all the ways to solve for smaller problems
waysOfDoingNcents[higherAmount] += waysOfDoingNcents[higherAmountRemainder];
}
}
return waysOfDoingNcents[amount];
}
var denominations = [1, 2, 3];
var amount = 4;
console.log(waysToReturnChange(denominations, denominations.length - 1, amount));
console.log(waysToReturnMemoize(amount,denominations));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment