Java Backtracking solution beats 97%


  • 0
    B

    '''

    boolean res = false;
    double eps = 1e-5;   
    public boolean judgePoint24(int[] nums) {
        double[] arr = new double[nums.length];
        for (int i = 0; i < nums.length; i++) {
            arr[i] = (double)nums[i];
        }
        helper(arr, nums.length);
        return res;
    }
    
    public void helper(double[] arr, int n) {
        if (res == true) {
            return;
        }
        if (n == 1) {
            if (Math.abs(arr[0] - 24.0) < eps) {
                res = true;
            }
            return;
        }
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                double a = arr[i];
                double b = arr[j];
                
                arr[j] = arr[n - 1];
                arr[i] = a + b;
                helper(arr, n - 1);
                
                arr[i] = a * b;
                helper(arr, n - 1);
                
                arr[i] = a - b;
                helper(arr, n - 1);
                
                arr[i] = b - a;
                helper(arr, n - 1);
                
                if (a != 0) {
                    arr[i] = b / a;
                    helper(arr, n - 1);
                }
                
                if (b != 0) {
                    arr[i] = a / b;
                    helper(arr, n - 1);
                }
                
                arr[j] = b;
                arr[i] = a;
            }
        }
    }
    

    '''


Log in to reply
 

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