L2-056 被n整除的n位数
解题思路
本题难点在于理解题意,和敢于dfs的勇气
直接上代码
#include<iostream>
#include<algorithm>
using namespace std;
//不如直接求出n位数以内的所有数谁能够被n整除
typedef long long ll;
ll n,a,b;
bool f = false;
ll res = 0;
void dfs(int step)
{
if(step == n)
{
if(res >= a && res <= b)
{
f = true;
cout<<res<<endl;
}
return ;
}
for(int i = 0 ; i <= 9 ; i ++)
{
if(step == 0 && i == 0) continue;//第一位不能是0
res = res * 10 + i;//选一个数
if(res % (step + 1) == 0)//如果当前位是合法的,即能被step + 1整除,就进入下一位的搜索
{
dfs(step + 1);
}
res /= 10;//改变全局变量需要回溯
}
}
int main()
{
cin>>n;
cin>>a>>b;
//暴力枚举
dfs(0);
if(!f) cout<<"No Solution"<<endl;
return 0;
}

浙公网安备 33010602011771号