题解 | #24点游戏算法#
24点游戏算法
https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
每次都从nums[0]开始竟然也可以过
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextInt()) { // 注意 while 处理多个 case int[] nums = new int[4]; for (int i = 0; i < 4; i++) { nums[i] = in.nextInt(); } boolean[] v = new boolean[4]; System.out.println(backtrack(nums, v, nums[0])); } } private static boolean backtrack(int[] nums, boolean[] visited, double res) { if (res == 24) { return true; } for (int i = 1; i < nums.length; i++) { if (!visited[i]) { visited[i] = true; if (backtrack(nums, visited, res + nums[i]) || backtrack(nums, visited, res - nums[i]) || backtrack(nums, visited, res * nums[i]) || backtrack(nums, visited, res / nums[i])) { return true; } visited[i] = false; } } return false; } }