1. 程式人生 > >輸出一個整數的全排列

輸出一個整數的全排列

out 時間 return 反思 std blog log include 屬於

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 // 數組a用來保存一種排列,也就是說100以內數(不包括100)的排列
 5 int a[100], n, count = 0;
 6 // 交換數組中的兩個元素
 7 void swap(int t1, int t2)
 8 {
 9     int temp;
10     temp = a[t1];
11     a[t1] = a[t2];
12     a[t2] = temp;
13 }
14 // 用來輸出一種排列
15 void output()
16 { 17 int j; 18 printf("\n"); 19 for(j = 1; j <= n; ++j) 20 printf("%d ", a[j]); 21 ++count; 22 } 23 void try(int t) 24 { 25 int j; 26 if(t > n) 27 output(); 28 else 29 for(j = t; j <= n; ++j) 30 { 31 swap(t, j);
32 try(t + 1); 33 // 回溯時,恢復原來的排列,註意回溯的位置 34 swap(t, j); 35 } 36 } 37 // 該算法的時間復雜度為O(n!) 38 // 輸出整數n的全排列 39 int main() 40 { 41 int i; 42 printf("Please input permutation number :\n"); 43 scanf("%d", &n); 44 for(i = 1; i <= n; ++i)
45 a[i] = i; 46 try(1); 47 printf("\ncount = %d", count); 48 return 0; 49 }

當你發現自己屬於大多數人這邊的時候,都該停下來反思一下

輸出一個整數的全排列