题解 | #24点运算#
24点运算
https://www.nowcoder.com/practice/7e124483271e4c979a82eb2956544f9d
import java.util.HashMap; import java.util.Scanner; public class Main { static HashMap<String, Integer> map = new HashMap<String, Integer>() { { put("A", 1); put("2", 2); put("3", 3); put("4", 4); put("5", 5); put("6", 6); put("7", 7); put("8", 8); put("9", 9); put("10", 10); put("J", 11); put("Q", 12); put("K", 13); } }; public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); String input = sc.nextLine(); if (input.contains("joker") || input.contains("JOKER")) { System.out.println("ERROR"); } else { String[] arr = input.split(" "); if (dfs(arr, new int[] {1, 0, 0, 0}, arr[0], map.get(arr[0])) || dfs(arr, new int[] {0, 1, 0, 0}, arr[1], map.get(arr[1])) || dfs(arr, new int[] {0, 0, 1, 0}, arr[2], map.get(arr[2])) || dfs(arr, new int[] {0, 0, 0, 1}, arr[3], map.get(arr[3])) ) { } else { System.out.println("NONE"); } } } static boolean dfs(String[] arr, int[] visited, String func, int curVal) { int sum = 0; for (int i = 0; i < 4; i++) { sum += visited[i]; } if (curVal == 24 & sum == 4) { System.out.println(func); return true; } for (int i = 0; i < 4; i++) { if (visited[i] == 0) { visited[i] = 1; if (dfs(arr, visited.clone(), func + "+" + arr[i], curVal + map.get(arr[i]))) { return true; } if (dfs(arr, visited.clone(), func + "-" + arr[i], curVal - map.get(arr[i]))) { return true; } if (dfs(arr, visited.clone(), func + "*" + arr[i], curVal * map.get(arr[i]))) { return true; } if (dfs(arr, visited.clone(), func + "/" + arr[i], curVal / map.get(arr[i]))) { return true; } visited[i] = 0; } } return false; } }