我只说个0 1 2 3 四个数字的
int a,a1,a2,......a9,TATOL;
for(a=1;a<=3;a++)//第一位
for(a1=0;a1<=3;a1++)
if(a1!=a)
for(a2=0;a2<=3;a2++)
if(a2!=a1&&a2!=a)
for(a3=1;a3<=3;a3+=2)
if (a3!=a2&&a3!=a1&&a3!=a)
TATOL++;
printf("%d",TATOL);
#include <stdio.h> void permutation(char a[], int m, int n) { int i; char t; if (m<n-1) { permutation(a, m+1, n); for (i=m+1;i<n;i++) { t=a[m]; a[m]=a[i]; a[i]=t; permutation(a, m+1, n); t=a[m]; a[m]=a[i]; a[i]=t; } } else { printf("%s\n", a); } }
int main() { char a[]="ABCDE"; permutation(a, 0,5); return 0; }
这是网上看来的(在那里我忘了),它的算法和大众不大一样,值得看看
楼上的算法是自己写的吧
这种牺牲时间来换取空间的做法,我不是很赞成。(个人意见,请指教)
[此贴子已经被作者于2004-06-11 00:28:19编辑过]
// c++ code
#include <iostream> #include <string> #include <cstdlib> #include <algorithm>
using namespace std;
int main() { string num = "01234567"; string first, last; int firstNum, lastNum; sort(num.begin(), num.end()); int cnt = 0; do { first = num.at(0); last = num.at(7);
firstNum = atoi(first.c_str()); lastNum = atoi(last.c_str());
if(firstNum != 0 && lastNum%2 != 0) cnt++; }while (next_permutation(num.begin(), num.end())); cout<<cnt<<endl;
system("pause"); return 0; }
#include <iostream> #include <string> #include <algorithm> #include <cstdlib>
using namespace std;
int main() { string code = "123456789"; string temp; int num[9]; int cnt = 0;
sort(code.begin(), code.end()); do { for(int i = 0; i<9; i++) { temp = code.at(i); num[i] = atoi(temp.c_str()); } int sum1 = num[0] + num[1] + num[2]; int sum2 = num[3] + num[4] + num[5]; if(sum1 == sum2) { int sum3 = num[6] + num[7] + num[8]; if(sum2 == sum3) { int sum4 = num[0] + num[3] + num[6]; if(sum3 == sum4) { int sum5 = num[1] + num[4] + num[7]; if(sum4 == sum5) { int sum6 = num[2] + num[5] + num[8]; if(sum5 == sum6) { int sum7 = num[2] + num[4] + num[6]; if(sum6 == sum7) { int sum8 = num[0] + num[4] + num[8]; if(sum7 == sum8) { cout<<num[0]<<num[1]<<num[2]<<endl; cout<<num[3]<<num[4]<<num[5]<<endl; cout<<num[6]<<num[7]<<num[8]<<endl; cout<<endl; cnt++; } } } } } } } }while (next_permutation(code.begin(), code.end())); cout<<cnt;
system("pause"); return 0; }
这是knocker的程序:
#include <stdio.h> void main() { int a,b,c,d,n=0; for(a=1;a<4;a++)//第一位数从1开始循环, for(b=0;b<4;b++)//第二数从0开始循环, for(c=0;c<4;c++)//第三位数从0开始循环, for(d=1;d<4;d++)//第四位数从0开始循环, if(b!=a&&c!=b&&c!=a&&d!=c&&d!=b&&d!=a)//让他们互不相等; { n++;//统计个数; printf("%d%d%d%d ",a,b,c,d);//将它们打印出来; } printf("\nn=%d",n); printf("\n"); }
[此贴子已经被作者于2004-06-11 21:34:27编辑过]