sub partition {
print "@_\n";
my ( $largest, @rest ) = @_;
my $min = $rest[0] || 1;
my $max = int( $largest / 2 );
for my $n ( $min .. $max ) {
partition( $largest - $n, $n, @rest );
}
}
我在互联网上发现这个代码,如果用作打印所有可能的分区
&partition(number)
但我希望它将所有可能的分区分配给a
名为$numbers
的变量。任何人都可以修改它,使其像这样:
&partition(3);
#and assigns them to $numbers like this
$numbers = "1+1+1:1+2:2+1";
上面的代码打印了每个可能的分区,但它找不到 每种可能的组合。
答案 0 :(得分:0)
方法1:
sub partition {
my @partitions = join("+", @_);
my ( $largest, @rest ) = @_;
my $min = $rest[0] || 1;
my $max = int( $largest / 2 );
for my $n ( $min .. $max ) {
push @partitions, partition( $largest - $n, $n, @rest );
}
return join(':', @partitions);
}
方法2 :(使用更少的内存)
sub partition {
my @partitions;
local *_partition = sub {
push @partitions, join("+", @_);
my ( $largest, @rest ) = @_;
my $min = $rest[0] || 1;
my $max = int( $largest / 2 );
for my $n ( $min .. $max ) {
_partition( $largest - $n, $n, @rest );
}
};
_partition(@_);
return join(':', @partitions);
}