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};
    }

你可能感兴趣的:(leetcode,算法,leetcode)