Why does this difference changes the performance so much in C?


  • 0
    H

    First version 3ms:

    bool helper(int* nums, int numsSize, int point, bool round){
        if(numsSize <= 0){
            if(round && point==0) return true;
            if(point>0) return true;
            else return false;
        }
        return (!helper(nums+1, numsSize-1, -(point + nums[0]), !round) || !helper(nums, numsSize-1, -(point + nums[numsSize-1]), !round));
    }
    
    bool PredictTheWinner(int* nums, int numsSize) {
        return helper(nums, numsSize, 0, true);
    }
    

    Second Version 159ms:

    bool helper(int* nums, int numsSize, int point, bool round){
        if(numsSize <= 0){
            if(round && point==0) return true;
            if(point>0) return true;
            else return false;
        }
        int a = !helper(nums+1, numsSize-1, -(point + nums[0]), !round);
        int b = !helper(nums, numsSize-1, -(point + nums[numsSize-1]), !round);
        return  (a||b);
    }
    
    bool PredictTheWinner(int* nums, int numsSize) {
        return helper(nums, numsSize, 0, true);
    }
    

    Why just a little change in my helper function for storing the return value changes the performance a lot?


  • 0
    G

    @HsiangWei

    The first one , if the first half of the return of the helper function is true, it stops and return. But the second will ask the program to get both return value and give it to a and b and then return (a || b). FYI


Log in to reply
 

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