TimeLimitExceeded error


  • 4

    Hey guys,
    I just encounter this time limit exceed error. I have tested several inputs and it was working correctly. But when I submitted this error came out.
    I searched the Discussion and it seems that everybody built a new array to implement, for example, result[i] = result[i-1] + result[i-2]. But why cannot we just use recursive directly, climbStairs(n) = climbStairs(n-1) + climbStairs(n-2)? Anybody could help me out please?

    public class Solution {
    public int climbStairs(int n) {

        // if step == 0, return 1, that there is only one method to reach the top
        if(n == 0) return 1;
        // if the steps are 1 or 2, there are 1 or 2 methods to reach the top, respectively
        // 1 : 1
        // 2 : 1+1 or 2
        if(n == 1) return 1;
        // for steps over 2, apply recursive algorithm 
        return climbStairs(n-1) + climbStairs(n-2);
    
    }
    

    }


  • 1
    M

    You should know why we use Dynamic Programming.


  • 0

    Could you explain more please? I am novice of Java. I really appreciated!


  • 0

    I mean, when I worked on Hanoi problem, this recursive implementation worked perfectly. But here in this question, cannot figure out what is wrong with the recursive algorithm. Any difference between these two questions....


Log in to reply
 

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