你有 4 張寫有 1 到 9 數字的牌。你須要判斷是否能經過 *,/,+,-,(,) 的運算獲得 24。 java
示例 1: spa
輸入: [4, 1, 8, 7] code
輸出: True blog
解釋: (8-4) * (7-1) = 24 遊戲
示例 2: rem
輸入: [1, 2, 1, 2] get
輸出: False io
注意: class
回溯法考慮每一種狀況import
1 import java.util.ArrayList; 2 3 class Solution { 4 public boolean judgePoint24(int[] nums) { 5 ArrayList A = new ArrayList<Double>(); 6 for (int v: nums) A.add((double) v); 7 return solve(A); 8 } 9 private boolean solve(ArrayList<Double> nums) { 10 if (nums.size() == 0) return false; 11 if (nums.size() == 1) return Math.abs(nums.get(0) - 24) < 1e-6; 12 for (int i = 0; i < nums.size(); i++) { 13 for (int j = 0; j < nums.size(); j++) { 14 if (i != j) { 15 ArrayList<Double> nums2 = new ArrayList<Double>(); 16 for (int k = 0; k < nums.size(); k++) if (k != i && k != j) { 17 nums2.add(nums.get(k)); 18 } 19 for (int k = 0; k < 4; k++) { 20 if (k < 2 && j > i) continue; 21 if (k == 0) nums2.add(nums.get(i) + nums.get(j)); 22 if (k == 1) nums2.add(nums.get(i) * nums.get(j)); 23 if (k == 2) nums2.add(nums.get(i) - nums.get(j)); 24 if (k == 3) { 25 if (nums.get(j) != 0) { 26 nums2.add(nums.get(i) / nums.get(j)); 27 } else { 28 continue; 29 } 30 } 31 if (solve(nums2)) return true; 32 nums2.remove(nums2.size() - 1); 33 } 34 } 35 } 36 } 37 return false; 38 } 39 }