LeetCode 679. 24 Game

Posted Dylan_Java_NYC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 679. 24 Game相关的知识,希望对你有一定的参考价值。

原题链接在这里: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的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 679. 24 Game(回溯法)

LeetCode题679 —— 24 Game

Leetcode之深度优先搜索&回溯专题-679. 24 点游戏(24 Game)

leetcode679. 24 Game

java 679. 24 Game.java

Leetcode 679.24点游戏