全排列
时间限制: 1 Sec 内存限制: 128 MB
题目描述
对1~ n 的 n个整数进行全排列(n<=9),编写程序输出所有可能的排列组合. 用递归算法实现.
输入
输入n
输出
输入n个整数的所有可能的排列组合.
样例输入
3
样例输出
1 2 3
1 3 2
2 1 3
2 3 1
3 2 1
3 1 2
提示
输出时用,%4d
1 #include <iostream> 2 #include <stdio.h> 3 using namespace std; 4 int a[100]; 5 void Perm(int list[],int k,int m) 6 { 7 if(k == m){ 8 for(int i = 0;i <= m;i++) 9 printf(" %d",list[i]); 10 printf(" "); 11 } 12 else 13 for(int i = k; i <= m;i++) 14 { 15 swap(list[k],list[i]); 16 Perm(list,k+1,m); 17 swap(list[k],list[i]); 18 } 19 } 20 21 int main() 22 { 23 int n; 24 cin >> n; 25 for(int i = 0; i < n;i++) 26 { 27 a[i] = i+1; 28 } 29 Perm(a,0,n-1); 30 return 0; 31 }