本帖最后由 523066680 于 2017-4-8 13:20 编辑
C语言已忘光,代码毫无新意 | #include <stdio.h> | | #include <stdlib.h> | | #include <string.h> | | | | void f(char *oldstr, char *newstr, int len, int lv) | | { | | char *ostr = (char *)malloc( len * sizeof(char) ); | | for (int i = 0; i < len; i++) | | { | | strcpy( ostr, oldstr ); | | | | newstr[lv] = ostr[i]; | | newstr[lv+1] = '\0'; | | if (len == 1) | | printf("%s \n", newstr); | | | | for (int j = i; j < (len-1); j++) | | ostr[j] = ostr[j+1]; | | | | if ( len > 0 ) | | f( ostr, newstr, len-1, lv+1 ); | | | | } | | } | | | | int main(int argc, char *argv[]) | | { | | char oldstr[] = "bathome"; | | char *newstr = (char *)malloc( (strlen(oldstr)+1) * sizeof(char) ); | | f(oldstr, newstr, strlen(oldstr), 0); | | | | return 0; | | }COPY |
Perl (不借用外部模块) | my @cup; | | my @nums; | | our $len; | | @nums = (split("", "bathome")); | | $len = $#nums+1; | | | | &func(\@cup, \@nums); | | | | sub func | | { | | my ($a, $b) = (shift, shift); | | my @ar; | | my @br; | | | | print join(",", @{$a}),"\n" if ( scalar(@{$a}) == $len ); | | | | for my $i ( 0 .. $#{$b} ) | | { | | @ar = (@{$a}, $b->[$i]); | | @br = @{$b}[0..$i-1, $i+1..$#{$b}]; | | &func(\@ar, \@br); | | } | | }COPY |
以下拷贝自《High-Order Perl》 | sub permute | | { | | my @items = @{ $_[0] }; | | my @perms = @{ $_[1] }; | | unless (@items) | | { | | print join("", @perms) ,"\n"; | | } | | else | | { | | my(@newitems,@newperms,$i); | | for $i (0 .. $#items) | | { | | @newitems = @items; | | @newperms = @perms; | | unshift(@newperms, splice(@newitems, $i, 1)); | | permute([@newitems], [@newperms]); | | } | | } | | } | | | | | | permute([qw(b a t h o m e)], []);COPY |
《High-Order Perl》里面有更有趣的思路,午休,有空再更 |