天天看點

24點遊戲java實作

24 點遊戲

https://leetcode-cn.com/problems/24-game/

你有 4 張寫有 1 到 9 數字的牌。你需要判斷是否能通過 *,/,+,-,(,) 的運算得到 24。

示例 1:

輸入: [4, 1, 8, 7]

輸出: True

解釋: (8-4) * (7-1) = 24

示例 2:

輸入: [1, 2, 1, 2]

輸出: False

注意:

除法運算符 / 表示實數除法,而不是整數除法。例如 4 / (1 - 2/3) = 12 。

每個運算符對兩個數進行運算。特别是我們不能用 - 作為一進制運算符。例如,[1, 1, 1, 1] 作為輸入時,表達式 -1 - 1 - 1 - 1 是不允許的。

你不能将數字連接配接在一起。例如,輸入為 [1, 2, 1, 2] 時,不能寫成 12 + 12 。

思路:套娃。。

class Solution {
    public boolean judgePoint24(int[] nums) {
        double a=nums[0];
        double b=nums[1];
        double c=nums[2];
        double d=nums[3];
        return junge(a,b,c,d); 
    }
    public boolean junge(double a,double b,double c,double d){
        return 
        //a b
        junge(a+b,c,d)||
        junge(a*b,c,d)||
        junge(a-b,c,d)||
        junge(b-a,c,d)||
        junge(a/b,c,d)||
        junge(b/a,c,d)||
        //a c
        junge(a+c,b,d)||
        junge(a*c,b,d)||
        junge(c-a,b,d)||
        junge(a-c,b,d)||
        junge(a/c,b,d)||
        junge(c/a,b,d)||
        //a d
        junge(a+d,b,c)||
        junge(a*d,b,c)||
        junge(d-a,b,c)||
        junge(a-d,b,c)||
        junge(a/d,b,c)||
        junge(d/a,b,c)||
        //b c
        junge(c+b,a,d)||
        junge(c*b,a,d)||
        junge(c-b,a,d)||
        junge(b-c,a,d)||
        junge(c/b,a,d)||
        junge(b/c,a,d)||
        //b d
        junge(d+b,a,c)||
        junge(d*b,a,c)||
        junge(d-b,a,c)||
        junge(b-d,a,c)||
        junge(d/b,a,c)||
        junge(b/d,a,c)||
         //c d
        junge(d+c,a,b)||
        junge(d*c,a,b)||
        junge(d-c,a,b)||
        junge(c-d,a,b)||
        junge(d/c,a,b)||
        junge(c/d,a,b);
    }
    public boolean junge(double a,double b,double c){
        return 
        //a b
        junge(a+b,c)||
        junge(a*b,c)||
        junge(a-b,c)||
        junge(b-a,c)||
        junge(a/b,c)||
        junge(b/a,c)||
        //a c
        junge(a+c,b)||
        junge(a*c,b)||
        junge(a-c,b)||
        junge(c-a,b)||
        junge(a/c,b)||
        junge(c/a,b)||
         //b c
        junge(b+c,a)||
        junge(b*c,a)||
        junge(b-c,a)||
        junge(c-b,a)||
        junge(b/c,a)||
        junge(c/b,a);
    }
    public boolean junge(double a,double b){
        return
        //判斷是否等于24要通過作差取絕對值再和極小值比較的方式實作
        Math.abs(a+b-24)<0.000001||
        Math.abs(a*b-24)<0.000001||
        Math.abs(a-b-24)<0.000001||
        Math.abs(b-a-24)<0.000001||
        Math.abs(a/b-24)<0.000001||
        Math.abs(b/a-24)<0.000001;
    }
}