题解 | #24点游戏算法#
24点游戏算法
https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { static boolean exist = false; public static void main(String[] args) { Scanner in = new Scanner(System.in); int[] nums = new int[4]; nums[0] = in.nextInt(); nums[1] = in.nextInt(); nums[2] = in.nextInt(); nums[3] = in.nextInt(); boolean[] used = new boolean[4]; dfs(nums, used, 0, 0); System.out.print(exist); } private static void dfs(int[] nums, boolean[] used, double target, int index) { if (index == 4) { if (target == 24) { exist = true; } return; } for (int i = 0; i < 4; i++) { if (!used[i]) { used[i] = true; dfs(nums, used, target + nums[i], index + 1); dfs(nums, used, target - nums[i], index + 1); dfs(nums, used, target * nums[i], index + 1); dfs(nums, used, target / nums[i], index + 1); used[i] = false; } } } }