Easy understanding java backtracking


  • 0
    W
    class Solution {
    public boolean judgePoint24(int[] nums) {
        if(nums == null || nums.length != 4) return false;
        double[] copy = new double[4];
        for(int i = 0; i < 4; i++){
            copy[i] = nums[i];
        }
        return help(copy, 4);
        
    }
    public boolean help(double[] copy, int n){
        if(n == 1){
            if(Math.abs(copy[0] - 24) < 0.000001){
                return true;
            }
        }
        for(int i = 0; i < n; i++){
            for(int j = i + 1; j < n; j++){
                double a;
                double b;
                a = copy[i];
                b = copy[j];
                copy[j] = copy[n - 1];
                copy[i] = a + b;
                if(help(copy, n - 1)) return true;
                copy[i] = a - b;
                if(help(copy, n - 1)) return true;
                copy[i] = b - a;
                if(help(copy, n - 1)) return true;
                copy[i] = a * b;
                if(help(copy, n - 1)) return true;
                if(a != 0){
                    copy[i] = b / a;
                    if(help(copy, n - 1)) return true;
                }
                if(b != 0){
                    copy[i] =  a / b;
                    if(help(copy, n - 1)) return true;
                }
                copy[i] = a;
                copy[j] = b;
        }
    }
        return false;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.