习题--排列(permutation)

题目:

用1,2,3,…,9组成3个三位数abc,def和ghi,每个数字恰好使用一次,要求:abc:def:ghi=1:2:3。按照"abc def ghi"的格式输出所有解,每行一个解。


思路一:

手写全排列有些复杂,因此首先通过比例关系确定abc, def, ghi,再检查他们是否是9个数字的全排列。
(1)循环遍历abc。由于abc的最小值为123, ghi的最大值为987,因此123 <= abc <= 987/3=329 ,减小计算复杂度。
(2)使用数组a[ ],判断是否9个数字是否重复使用。数组中存放对应数字的使用次数,未使用过为0。

代码:

#include <stdio.h>
#include <time.h>
using namespace std;
int main()
{
    for(int x=123;x<=329;x++)
     {
         int a[10]={0};
         
         int x1=x/100, x2=(x/10)%10, x3=x%10;
         
         if(x1==0 || x2==0 || x3==0) continue;
         a[x1]++;
         if(a[x2]==0) a[x2]++;
         else continue;
         if(a[x3]==0) a[x3]++;
         else continue;
         
         int y=2*x;
         int y1=y/100, y2=(y/10)%10, y3=y%10;
         
         if(y1==0 || y2==0 || y3==0) continue;
         if(a[y1]==0) a[y1]++;
         else continue;
         if(a[y2]==0) a[y2]++;
         else continue;
         if(a[y3]==0) a[y3]++;
         else continue;
         
         int z=3*x;
         int z1=z/100, z2=(z/10)%10, z3=z%10;
         
         if(z1==0 || z2==0 || z3==0) continue;
         if(a[z1]==0) a[z1]++;
         else continue;
         if(a[z2]==0) a[z2]++;
         else continue;
         if(a[z3]==0) a[z3]++;
         else continue;
         
         printf("%d %d %d\n",x,y,z);
     }
     printf("Time used = %.4f\n",(double)clock()/CLOCKS_PER_SEC);
     return 0;
}

运行结果:

192 384 576
219 438 657
273 546 819
327 654 981
Time used = 0.2922
Program ended with exit code: 0

思路二:

从全排列入手,使用算法库中的全排列函数。
列举出全排列的所有数字,再判断是否存在1:2:3的比例关系。

代码:

#include <stdio.h>
#include <algorithm>
#include <time.h>
using namespace std;
int main()
{
    int a[9]={1,2,3,4,5,6,7,8,9};
    int x,y,z;
    do{
    x = a[0]*100+a[1]*10+a[2];
    y = a[3]*100+a[4]*10+a[5];
    z = a[6]*100+a[7]*10+a[8];
    if(y==2*x && z==3*x)
        printf("%d %d %d\n",x,y,z);
    }while(next_permutation(a,a+9) && x<329);
    printf("Time used = %.2f\n",(double)clock()/CLOCKS_PER_SEC);
    return 0;
}

运行结果:

192 384 576
219 438 657
273 546 819
327 654 981
Time used = 0.3080
Program ended with exit code: 0

两种方法运行时间差不多。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值