C语言描述:
#include <iostream> using namespace std; int A[101]; void print_permutation(int n, int *A, int cur) { if (cur == n) { //递归边界 for (int i = 0; i < n; i++) { printf("%d ", A[i]); } printf("\n"); } else { for (int i = 1; i <= n; i++) { //尝试在A[cur]中填各种整数i bool ok = true; //检查i是否被用过 for (int j = 0; j < cur; j++) { if (A[j] == i) { ok = false; //如果i已经在A[0]~A[cur-1]出现过,则不能再选 } } if (ok) { A[cur] = i; print_permutation(n, A, cur + 1); //递归调用 } } } } int main() { int n; scanf("%d", &n); print_permutation(n, A, 0); return 0; }
汇编语言:
INCLUDE Irvine32.inc .data arr dd 120 dup(?) ; arr dd 1,2,3,4,5,6,7,8,9,10 .code main PROC ; call readInt ; mov edx,eax mov eax,3 ;eax代表输入的数 push eax ;eax:count mov edx,offset arr ;edx:arr push edx call Assign ; mov edx,offset arr ; push edx ;edx:arr ; ; mov eax,edx ; push eax ;eax:count ; call output mov ecx,0 push eax push ecx push edx call FullPermutation exit main ENDP FullPermutation PROC push ebp mov ebp,esp pushad mov edx,[ebp+8] ;edx:arr mov esi,[ebp+12] ;esi:begin mov edi,[ebp+16] ;edi:end mov ecx,0 cmp esi,edi jl else1 again: cmp ecx,edi jge final mov eax,[edx+ecx*4] call writedec inc ecx jmp again else1: mov ecx,esi again1: cmp ecx,edi ;ecx:i jge final cmp esi,ecx je next1 push dword ptr [edx+esi*4] push dword ptr [edx+ecx*4] pop dword ptr [edx+esi*4] pop dword ptr [edx+ecx*4] next1: push edi mov eax,esi inc eax push eax push edx call FullPermutation cmp esi,ecx je next2 push dword ptr [edx+esi*4] push dword ptr [edx+ecx*4] pop dword ptr [edx+esi*4] pop dword ptr [edx+ecx*4] next2: inc ecx jmp again1 final: call crlf popad pop ebp ret 12 FullPermutation ENDP Assign PROC push ebp mov ebp,esp pushad mov ecx,[ebp+12] ;ecx:count mov edx,[ebp+8] ;edx:arr mov edi,0 again: cmp edi,ecx jge final mov eax,edi inc eax mov [edx+edi*4],eax inc edi jmp again final: popad pop ebp ret 8 Assign ENDP output PROC push ebp mov ebp,esp pushad mov edx,[ebp+12]; edx:arr mov ecx,[ebp+8]; ecx:count mov ebx,0 next: cmp ebx,ecx jge final mov eax,[edx+ebx*4] ; mov eax,ebx call writeint inc ebx jmp next final: popad ret 8 output ENDP END main
运行结果: