全排列问题(form.cpp)
【问题描述】
输出自然数 1 到 n 所有不重复的排列,即 n 的全排列,要求所产生的任一数字序列中不允许出现重复的数字。
【输入格式】 n(1≤n≤9)
【输出格式】 由 1~n 组成的所有不重复的数字序列,每行一个序列。
【输入样例】
3
【输出样例】
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
【分析】
这题两个思路:
1.STL
2.搜索
STL能更方便一点。
1 #include <cstdio> 2 #include <algorithm> 3 using namespace std; 4 5 int main() 6 { 7 int a[10],n,j; 8 scanf("%d",&n); 9 for(int i=1;i<=n;i++) 10 { 11 a[i]=i; 12 } 13 do{ 14 for(int k=1;k<=n;k++) 15 { 16 printf(" "); 17 printf("%d",a[k]); 18 } 19 printf(" "); 20 }while(next_permutation(a+1,a+n+1)); 21 return 0; 22 }