leetcode 679. 24 Game(游戏24点)

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

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

思路:
先说括号,括号其实是优先计算,可以实现为先选两个数计算,然后再和其他数计算。
然后是两个数的运算,加法和乘法没有顺序,减法和除法有顺序,所以两个数的计算会返回6个结果。
除法因为有小数部分,所以刚开始要把nums数组变为double类型,方便后面计算。

刚开始有4个数字,按顺序挑选两个计算,把计算的结果和剩下3个数字保存到一个新的数组,然后递归。
递归中有3个数字,按顺序挑两个计算,把计算的结果和剩下的1个数字保存到新数组,再递归。
直到新的数组只剩下一个数字,只需要和24比较,如果和24相等就返回true。
因为是double型,比较相等要看差的绝对值是否小于一个很小的数字。

    public boolean judgePoint24(int[] nums) {
        double[] dNums = new double[]{nums[0], nums[1], nums[2], nums[3]};
        return helper(dNums);
    }
    
    boolean helper(double[] nums) {
        if(nums.length == 1) return Math.abs(nums[0] - 24) < 0.0001;
        for(int i = 0; i < nums.length; i++) {
            for(int j = i+1; j < nums.length; j++) {
                double[] tmp = new double[nums.length - 1]; //两个数计算,剩下的保留
                //index是tmp的下标,k是nums的下标
                for(int k = 0, index = 0; k < nums.length; k++) {
                    if(k != i && k != j) { //两个计算的数放到末尾
                        tmp[index] = nums[k];
                        index ++;
                    }
                }
                for(double d : compute(nums[i], nums[j])) {
                    tmp[tmp.length-1] = d;
                    if(helper(tmp)) return true;
                }
            }
        }
        return false;       
    }
    
    double[] compute(double d1, double d2) {
        return new double[]{d1+d2, d1-d2, d2-d1, d1*d2, d1/d2, d2/d1};
    }

参考资料

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值