码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 679. 24 Game

时间:2020-01-16 14:51:19      阅读:97      评论:0      收藏:0      [点我收藏+]

标签: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:

  1. The division operator / represents real division, not integer division. For example, 4 / (1 - 2/3) = 12.
  2. 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.
  3. You cannot concatenate numbers together. For example, if the input is [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 }

LeetCode 679. 24 Game

标签:could   bsp   nbsp   orm   struct   numbers   real   you   public   

原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/12200645.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!