题解 | 24点运算
24点运算
https://www.nowcoder.com/practice/7e124483271e4c979a82eb2956544f9d
import java.io.*; import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { private static final Map<String, Integer> str2Int = new HashMap<>(); private static final String[] int2Str = new String[] {"", "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "k"}; private static char[] offerOps = new char[] {'+', '-', '*', '/'}; private static final List<int[]> orders = new ArrayList<>(); private static final int[] order = new int[4]; private static final boolean[] vis = new boolean[4]; private static final int[] nums = new int[4]; private static final char[] ops = new char[3]; private static final StringBuilder sb = new StringBuilder(); private static boolean end = false; static { str2Int.put("A", 1); str2Int.put("2", 2); str2Int.put("3", 3); str2Int.put("4", 4); str2Int.put("5", 5); str2Int.put("6", 6); str2Int.put("7", 7); str2Int.put("8", 8); str2Int.put("9", 9); str2Int.put("10", 10); str2Int.put("J", 11); str2Int.put("Q", 12); str2Int.put("K", 13); } public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String[] cards = bf.readLine().split(" "); for (String card : cards) if ("joker".equals(card) || "JOKER".equals(card)) { System.out.print("ERROR"); return; } for (int i = 0; i < 4; i++) nums[i] = str2Int.get(cards[i]); Arrays.sort(nums); dfs1(0); for (int i = 0; i < orders.size() && !end; i++) dfs2(orders.get(i), 0); if (sb.length() == 0) System.out.print("NONE"); else System.out.print(sb); } private static void dfs1(int idx) { if (idx == 4) { orders.add(order.clone()); return; } for (int i = 0; i < 4; i++) if (!vis[i] && (i == 0 || nums[i] != nums[i - 1] || vis[i - 1])) { vis[i] = true; order[idx] = nums[i]; dfs1(idx + 1); vis[i] = false; } } private static void dfs2(int[] arr, int idx) { if (idx == 3) { int sum = arr[0]; for (int i = 0; i < 3; i++) sum = compute(sum, arr[i + 1], ops[i]); if (sum == 24) { for (int i = 0; i < 3; i++) sb.append(int2Str[arr[i]]).append(ops[i]); sb.append(int2Str[arr[3]]); end = true; } return; } for (int i = 0; i < 4 && !end; i++) { ops[idx] = offerOps[i]; dfs2(arr, idx + 1); } } private static int compute(int a, int b, char op) { if (op == '+') return a + b; else if (op == '-') return a - b; else if (op == '*') return a * b; else return a / b; } }
}
这个测试系统是不是有问题,逗我玩呢,不如leetcode