sub Solve
{
my ($goal, $elements) = @_;
$elements = [ sort { $a <=> $b } @$elements ];
my (@results, $RecursiveSolve, $nextValue);
$RecursiveSolve = sub {
my ($currentGoal, $included, $index) = @_;
for ( ; $index < @$elements; ++$index) {
$nextValue = $elements->[$index];
if ($currentGoal > 2 * $nextValue) {
$RecursiveSolve->($currentGoal - $nextValue,
[ @$included, $nextValue ],
$index + 1);
} else {
push @results, [ @$included, $nextValue ]
if $currentGoal == $nextValue;
return if $nextValue >= $currentGoal;
}
}
};
$RecursiveSolve->($goal, [], 0);
undef $RecursiveSolve;
return @results;
}
my @results = Solve(7, [2,3,4,7]);
print "@$_\n" for @results;
It started as a fairly direct translation of the C # version from a question related to you , but I simplified it a bit (and now a bit more, and also removed some unnecessary variable distributions, added some optimizations based on the list of sorted elements and rebuilt the conditions to be a little more effective).
. , , , , . ( , , .) , , . ( 2, , .)