解题来源于蓝桥杯老师
题目要求如上
两种方法一种是用递归,另一种是用algorithm库函数中的全排列函数next_permutation具体代码如下:
#include <iostream>
#include <algorithm>
using namespace std;
int a[]={1,2,3,4,5,6,7,8,9};
int count=0,i,ans=0;
bool check()
{
int x=a[3]*100+a[4]*10+a[5];
int y=a[6]*100+a[7]*10+a[8];
if((a[1]*y+a[2]*x)%(y*a[2])==0 && a[0]+(a[1]*y+a[2]*x)/(y*a[2])==10)
return true;
return false;
}
//开始定义递归函数 ,递归函数是一种固定的模板 递归回溯生成全排列,适用于无重复元素的情况
void f (int k)
{
if(k==9)
{
if(check())
count++;
}
//从k往后的每个数字都可以放在k位
for(int i=k;i<9;i++)
{
{
int t=a[i];
a[i]=a[k];
a[k]=t;
}
f(k+1);//进行递归
//回溯
{
int t=a[i];
a[i]=a[k];
a[k]=t;
}
}
}
int main()
{
// f(0);
//第二种方法运用一个函数 求全排列
do{
if(check())
{
ans++;
}
}while(next_permutation(a,a+9));
cout<<ans<<endl;
return 0;
}