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 }

 

转载于:https://www.cnblogs.com/beiyeqingteng/p/10748005.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值