Created
August 20, 2018 12:56
-
-
Save XedinUnknown/3f13deb54c8ad63a13188636ea631639 to your computer and use it in GitHub Desktop.
Coin Change Problem
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 count_change ($money, $coins) { | |
sort($coins, SORT_NUMERIC); | |
$money = (int) $money; | |
$ways = array(); // ['denom' => [ 'value' => 'numWays' ]] | |
foreach ($coins as $_c => $_denom) { | |
for ($_m = 0; $_m <= $money; $_m++) { | |
if ($_m === 0) { | |
$ways[$_c][$_m] = 1; | |
continue; | |
} | |
if ($_m < $_denom) { | |
$numWays = isset($ways[$_c-1]) | |
? $ways[$_c-1][$_m] | |
: 0; | |
$ways[$_c][$_m] = $numWays; | |
continue; | |
} | |
$prevVal = $ways[$_c][$_m-$_denom]; | |
$prevDenom = $ways[$_c-1][$_m]; | |
$numWays = $prevVal + $prevDenom; | |
$ways[$_c][$_m] = $numWays; | |
} | |
} | |
return $ways[$_c][$money]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment