标签:could bsp nbsp orm struct numbers real you public
原题链接在这里:https://leetcode.com/problems/24-game/
题目:
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:
/
represents real division, not integer division. For example, 4 / (1 - 2/3) = 12.-
as a unary operator. For example, with [1, 1, 1, 1]
as input, the expression -1 - 1 - 1 - 1
is not allowed.[1, 2, 1, 2]
, we cannot write this as 12 + 12.题解:
Eventually, it is picking 2 numbers from array, any place, perform + - * / and get one result and use it with the rest numbers to construct a new array.
Until the new array size is 1.
Check if new array could from 24.
Time Complexity: exponential.
Space: O(nums.length). stack space.
AC Java:
1 class Solution { 2 public boolean judgePoint24(int[] nums) { 3 if(nums == null || nums.length == 0){ 4 return false; 5 } 6 7 double [] arr = new double[nums.length]; 8 for(int i = 0; i < nums.length; i++){ 9 arr[i] = nums[i]; 10 } 11 12 return dfs(arr); 13 } 14 15 private boolean dfs(double [] arr){ 16 if(arr.length == 1){ 17 return Math.abs(arr[0] - 24.0) < 0.001; 18 } 19 20 for(int i = 0; i < arr.length; i++){ 21 for(int j = i + 1; j < arr.length; j++){ 22 double [] next = new double[arr.length - 1]; 23 for(int k = 0, index = 0; k < arr.length; k++){ 24 if(k != i && k != j){ 25 next[index++] = arr[k]; 26 } 27 } 28 29 for(double d : compute(arr[i], arr[j])){ 30 next[next.length - 1] = d; 31 if(dfs(next)){ 32 return true; 33 } 34 } 35 } 36 } 37 38 return false; 39 } 40 41 private double[] compute(double x, double y){ 42 return new double[]{x + y, x - y, y - x, x * y, x / y, y / x}; 43 } 44 }
标签:could bsp nbsp orm struct numbers real you public
原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/12200645.html