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.

思路:把每两个数拿出来,找出其所有的加减乘除组合,然后把每一个取出来,后剩余的两个数(总共也就是3个数),继续做同样的操作,直到只剩下一个数,看那个数是不是24.

 1 class Solution {
 2     public boolean judgePoint24(int[] nums) {
 3         return helper(new double[] { nums[0], nums[1], nums[2], nums[3] });
 4     }
 5 
 6     private boolean helper(double[] nums) {
 7         if (nums.length == 1) return Math.abs(nums[0] - 24) < 0.01;
 8         for (int i = 0; i < nums.length; i++) {
 9             for (int j = i + 1; j < nums.length; j++) {
10                 double[] remainings = new double[nums.length - 1];
11                 int idx = 0;
12                 // add numbers in nums to remainings excluding nums[i] and nums[j]
13                 for (int k = 0; k < nums.length; k++) {
14                     if (k != i && k != j) {
15                         remainings[idx] = nums[k];
16                         idx++;
17                     }
18                 }
19                 for (double k : computeCombinations(nums[i], nums[j])) {
20                     remainings[remainings.length - 1] = k;
21                     if (helper(remainings)) {
22                         return true;
23                     }
24                 }
25             }
26         }
27         return false;
28     }
29 
30     private double[] computeCombinations(double a, double b) {
31         return new double[] { a + b, a - b, b - a, a * b, a / b, b / a };
32     }
33 }

 

posted @ 2019-04-22 01:04  北叶青藤  阅读(171)  评论(0编辑  收藏  举报