求输出1到10的所有种组合
1到10的所有组合共有10!种,怎样用C语言实现输出所有的排列组合?
[解决办法]
其实这个程序很简单,,用穷举法,镶嵌10层FOR循环就可以,,不过光输出的过程我的电脑运行了好长时间啊、、、、为了方便我给你后面加了个计数器、、、
#include<stdio.h>
main()
{
int a[10],i,b;
b=0;
for(i=0;i<10;i++)
a[i]=0;
for(a[0]=0;a[0]<10;a[0]++)
{for(a[1]=0;a[1]<10;a[1]++)
{for(a[2]=0;a[2]<10;a[2]++)
{for(a[3]=0;a[3]<10;a[3]++)
{for(a[4]=0;a[4]<10;a[4]++)
{for(a[5]=0;a[5]<10;a[5]++)
{for(a[6]=0;a[6]<10;a[6]++)
{for(a[7]=0;a[7]<10;a[7]++)
{for(a[8]=0;a[8]<10;a[8]++)
{for(a[9]=0;a[9]<10;a[9]++)
printf("%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d\n",a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],b++);
}
}
}
}
}
}
}
}
}
}
[解决办法]
参考下面的代码,在release模式下,计算10!种排列并全部存入到permutation.txt文件,在俺的机器上花了85秒钟左右。permutation.txt的大小为80+M。
#include <iostream>#include <fstream>#include <time.h>using namespace std; #define N 10int number[N] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};int temp[N];int total = 0;ofstream fos;// 会在E盘根目录下生成void write_file() { ++total; for(int i = 0; i < N; ++i) { fos << temp[i] << " "; } fos << endl;}void move(int offset, int i) /* 交换两个数 */{ int another; another = number[offset]; number[offset] = number[i]; number[i] = another;}void permutation(int offset, int count) /* 排列 */{ int i; if(count == 0) { write_file(); return; } else { for(i = offset; i < N; i++) { temp[offset] = number[i]; move(offset, i); permutation(offset+1, count-1); move(offset, i); } }} int main(){ clock_t start, finish; fos.open("E:/permutation.txt", ios::app); if(!fos) { cout << "can not open file..." << endl; exit(1); } cout << "Calculating started..." << endl; start = clock(); permutation(0, N); fos.close(); finish = clock(); cout << total << endl; int interval = (finish - start) * 1000 / CLOCKS_PER_SEC; cout << "Calculating stopped. It took " << interval << " ms." << endl;}
[解决办法]
兄弟,组合不就一种嘛,还求个毛线,排列才有10!种
#include<iostream>using namespace std;void f(int *a,int n){ if(n==9) { for(int i=0;i<10;i++) cout<<a[i]<<" "; cout<<endl; return ; } else { for(int k=n;k<10;k++) { swap(a[n],a[k]); f(a,n+1); swap(a[n],a[k]); } }}int main(){ int a[10]; for(int i=0;i<10;i++) a[i]=i+1; f(a,0); return 0;}