Recursion and Dynamic Programming
Coin Change (Bottom-Up)
Build a one-dimensional table where each amount stores the fewest coins needed to make it.
Algorithm
@steps
- Initialize
dp[0] = 0and all other amounts to an unreachable sentinel. - Scan amounts from
1through6. - For each coin, read the earlier cell
dp[amount - coin]when it exists. - Write the smallest candidate into the current amount.
- Print both the final answer and the full DP array. @end @complexity
- Time: O(target * coin_count)
- Space: O(target) @end
bottom-up dynamic programming
`dp[a]` is solved from already-computed smaller amounts, so every table cell has a visible dependency.
Perl DSA Implementation
basic.pl
use strict;
use warnings;
sub list_string { return "[" . join(", ", @_) . "]"; }
my @coins = (1, 3, 4);
my $target = 6;
my $inf = $target + 1;
my @dp = (($inf) x ($target + 1));
$dp[0] = 0;
for my $amount (1..$target) {
for my $coin (@coins) {
if ($amount >= $coin) {
my $candidate = $dp[$amount - $coin] + 1;
$dp[$amount] = $candidate if $candidate < $dp[$amount];
}
}
}
print "$dp[$target]\n";
print list_string(@dp) . "\n";
@end @output 2 [0, 1, 2, 1, 1, 2, 2] @end