in reply to problem while solving basic dynamic programming question
#!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11114280 use warnings; use List::Util qw( uniq ); my @cache = []; for my $n ( 3 .. 4 ) { print "$_\n" for sort @{ find($n) }; print "\n"; } sub find { my $n = shift; $cache[$n] //= [ uniq $n, map { my $nn = $_; map { my $t = $_; map "$t+$_", @{ find($nn) } } @{ find($n - $nn +) } } 1 .. $n - 1 ]; }
Outputs:
1+1+1 1+2 2+1 3 1+1+1+1 1+1+2 1+2+1 1+3 2+1+1 2+2 3+1 4
|
|---|