题解 | #跳石板#
跳石板
https://www.nowcoder.com/practice/4284c8f466814870bae7799a07d49ec8
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { int N = in.nextInt(); int M = in.nextInt(); int[] ret = new int[M + 1]; for (int i = 0; i <= M; i++) { //数组初始化 ret[i] = Integer.MAX_VALUE; } ret[N] = 0; for (int i = N; i < M; i++) { if (ret[i] == Integer.MAX_VALUE) { //表示小易不会到达这里 continue; } List<Integer> n = div(i);//求约数存到n中 for (int j : n) { if ( i + j <= M) { ret[i + j] = Math.min(ret[i + j], ret[i] + 1); //存最小值,最小步数 } } } if (ret[M] == Integer.MAX_VALUE) { //表示到达不了 System.out.println(-1); } else { System.out.println(ret[M]); } } } public static List<Integer> div(int n) { List<Integer> list = new ArrayList<>(); for (int i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) { list.add(i); if (n / i != i) { list.add(n / i); } } } return list; } }