Created
December 27, 2016 16:11
-
-
Save Arieg419/8593cb1802d27fab5219c1fd26e3f5e2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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