数字替换 java 暴搜+剪枝
🤠 原题地址

🤠 dfs 相较 bfs 容易剪枝
🐷 优化
🤠 从大到小枚举数 搜索顺序优化
🤠 记录目前最优方案,提前 return
🤠 当前步数+相差位数 >= 当前最优解 return
import java.io.*;
import java.util.*;
public class Main
{
static int INF = 10000;
static int n, ans = INF;
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws IOException
{
String[] split = in.readLine().split(" ");
n = Integer.parseInt(split[0]);
long x = Long.parseLong(split[1]);
dfs(x, 0);
if (ans == INF)
ans = -1;
System.out.println(ans);
}
/**
* @param x 当前值
* @param i 当前位数
*/
private static void dfs(long x, int d)
{
int cnt = 0;// 记录 x 的位数
boolean[] st = new boolean[10];// 记录 x 中是否有 2~8
for (long i = x; i != 0; i /= 10)
{
cnt++;
st[(int) (i % 10)] = true;
}
// 剪枝
// 当前位数 + (距目标位数的 位数) > 当前最优解
if (d + n - cnt >= ans)
return;
if (cnt == n)// 递归出口
{
ans = d;
return;
}
// 递归
for (int i = 9; i >= 2; i--)
{
if (st[i])
dfs(x * i, d + 1);
}
}
}

浙公网安备 33010602011771号