Acwing 4868. 数字替换 java DFS 剪枝

🤠 原题地址
在这里插入图片描述
在这里插入图片描述

🤠 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);
		}
	}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值