leetcode 679. 24 Game(遊戲24點)

藍羽飛鳥發表於2021-01-03

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

相關文章