LoginSignup
2
3

More than 5 years have passed since last update.

順列列挙(再帰版)

Posted at

以前書いたのはSTLをコピーした反復版だったが、再帰版は以下。Perlはシンプル。

permutation.pl
sub permutation {
    my ($first, @rest) = @_; 
    @rest or return [[@_]];

    my @result;
    for (@_) {
        push @rest, $first;
        $first = shift @rest;
        push @result , [$first, @$_]
            for @{permutation(@rest)};
    }   
    return [@result];
}

print @$_ , "\n"
    for @{permutation(1..4)};
2431
2413
2143
2134
2314
2341
3142
3124
3214
3241
3421
3412
4213
4231
4321
4312
4132
4123
1324
1342
1432
1423
1243
1234
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3