You have 4 cards each containing a number from 1 to 9. You need to judge whether they could operated through *, /, +, -, (, ) to get the value of 24. Example 1: Input: [4, 1, 8, 7] Output: True Explanation: (8-4) * (7-1) = 24 Example 2: Input: [1, 2, 1, 2] Output: False Note: The division operator / represents real division, not integer division. For example, 4 / (1 - 2/3) = 12. Every operation done is between two numbers. In particular, we cannot use - as a unary operator. For example, with [1, 1, 1, 1] as input, the expression -1 - 1 - 1 - 1 is not allowed. You cannot concatenate numbers together. For example, if the input is [1, 2, 1, 2], we cannot write this as 12 + 12.
Backtracking: every time draw two cards, calculate the possible results, and add one result to the nextRound list.
The nextRound list will have the remaining unused cards.
Every round the nextRound list will decrease its size by 1.
Repeat the process until nextRound list decrease to size 1.
1 class Solution { 2 public boolean judgePoint24(int[] nums) { 3 List<Double> list = new ArrayList<>(); 4 for (int num : nums) { 5 list.add((double)num); 6 } 7 return backtracking(list); 8 } 9 10 public boolean backtracking(List<Double> list) { 11 if (list.size() == 1) { 12 if (Math.abs(list.get(0) - 24.0) < 0.001) { 13 return true; 14 } 15 return false; 16 } 17 18 // every time backtracking: always draw two cards 19 for (int i = 0; i < list.size(); i ++) { 20 for (int j = i + 1; j < list.size(); j ++) { 21 22 // for each possible result of the two card-combination 23 for (double c : compute(list.get(i), list.get(j))) { 24 List<Double> nextRound = new ArrayList<>(); 25 nextRound.add(c); 26 27 for (int k = 0; k < list.size(); k ++) { 28 if (k != i && k != j) 29 nextRound.add(list.get(k)); 30 } 31 32 if (backtracking(nextRound)) return true; 33 } 34 } 35 } 36 return false; 37 } 38 39 // compute the possible result of a combination 40 public List<Double> compute(double a, double b) { 41 return Arrays.asList(a + b, a - b, b - a, a * b, a / b, b / a); 42 } 43 }