forked from AllAlgorithms/php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CoinChange.php
46 lines (37 loc) · 1.31 KB
/
CoinChange.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php
class CoinChange
{
const LENGTH = 15;
function __construct($coins)
{
$this->coins = $coins;
$this->memos = [];
// Prepare Array
for ($i = 0; $i < self::LENGTH; $i++)
{
array_push($this->memos, array());
for ($j = 0; $j < self::LENGTH; $j++)
{
array_push($this->memos[$i], array());
$this->memos[$i][$j] = -1;
}
}
}
function coin_change($current_index, $current_value)
{
if ($current_index >= count($this->coins) || $current_value < 0)
return 0;
if ($current_value == 0)
return 1;
if ($this->memos[$current_index][$current_value] != -1)
return $this->memos[$current_index][$current_value];
$total_ways = 0;
$total_ways += $this->coin_change($current_index, $current_value - $this->coins[$current_index]);
$total_ways += $this->coin_change($current_index + 1, $current_value);
$this->memos[$current_index][$current_value] = $total_ways;
return $total_ways;
}
}
$coin_change_calculator = new CoinChange([2, 3, 5]);
$total_ways = $coin_change_calculator->coin_change(0, 7);
echo sprintf("Total Ways To Return %d is %d", 7, $total_ways);