一、题目链接
二、题目分析
(一)算法标签
DFS 递归 剪枝 搜索
(二)解题思路
详细了解搜索类题目(DFS、BFS),请移步DFS BFS 搜索题目归纳
三、AC代码
解法一:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int n;
int ans;
bool used[10], backup[10];
bool check(int a, int c)
{
long long b = (long long)c * (n - a);
if (!a || !b || !c) return false;
memcpy(backup, used, sizeof used);
while (b)
{
int x = b % 10;
b /= 10;
if (!x || backup[x]) return false;
backup[x] = true;
}
for (int i = 1; i <= 9; i ++ )
if (!backup[i])
return false;
return true;
}
void dfs_c(int u, int a, int c) // u表示当前用了几个数字, a表示当前的a是多少, c表示当前的c是多少
{
if (u > 9) return;
if (check(a, c)) ans ++ ;
for (int i = 1; i <= 9; i ++)
{
if (!used[i])
{
used[i] = true;
dfs_c(u + 1, a, c * 10 + i);
used[i] = false;
}
}
}
void dfs_a(int u, int a) // u表示当前用了几个数字, a表示当前的数是多少
{
if (u > 9) return;
if (a >= n) return;
if (a) dfs_c(u, a, 0);
for (int i = 1; i <= 9; i ++ )
{
if (!used[i])
{
used[i] = true;
dfs_a(u + 1, a * 10 + i);
used[i] = false;
}
}
}
int main()
{
cin >> n;
dfs_a(0, 0);
cout << ans;
return 0;
}
二刷注意事项:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
bool st[10], backup[10];
int ans;
int n;
bool check(int a, int c)
{
LL b = (LL)n * c - a * c;
if (!a || !b || !c) return false;
memcpy(backup, st, sizeof st);
while (b)
{
int x = b % 10;
// !!注意1:不要忘了x有可能等于0
if (backup[x] || !x) return false;
backup[x] = true;
b /= 10;
}
for (int i = 1; i <= 9; i ++ )
if (!backup[i]) return false;
return true;
}
void dfs_c(int cnt, int a, int c)
{
if (cnt >= 9) return;
if (check(a, c)) ans ++ ;
for (int i = 1; i <= 9; i ++ )
{
if (!st[i])
{
st[i] = true;
// !!注意2:第三个参数也可以是c + 10 * i
dfs_c(cnt + 1, a, i + 10 * c);
st[i] = false;
}
}
}
void dfs_a(int cnt, int a)
{
if (cnt >= 9) return;
if (a >= n) return;
dfs_c(cnt, a, 0);
for (int i = 1; i <= 9; i ++ )
{
if (!st[i])
{
st[i] = true;
// !!注意3:第二个参数也可以是a + 10 * i,但要与注意2 对应!!
dfs_a(cnt + 1, i + 10 * a);
st[i] = false;
}
}
}
int main()
{
cin >> n;
dfs_a(0, 0);
cout << ans << endl;
return 0;
}