0

I know about the button up approach but I am trying to solve it with memoization and using an array instead of hashmap which you can find on the internet. But, apparently using an array causes Time Limit Exceeded error on leetcode but it shouldn't and I cannot figure out what the problem is. Anyone has any opinion why my code fails to submit?

class Solution {
    
    public int climbStairs(int n) {
        if(n<3) return n;
        Integer[] dp= new Integer[n+1];
        return climbStairs(n,dp);
    }
    
    private int climbStairs(int n,Integer[]dp){
        if(n<3) return n;
        if(dp[n]!=null) return dp[n];
        
        int step1=climbStairs(n-2);
        int step2=climbStairs(n-1);
        dp[n]=step1+step2;
        return dp[n];
    }
}
1
  • 1
    Sorry, but these online code challenges all make very bad questions: You're asking about some unspecified external code rates your code as bad in some way. That's not a question about your code! Please read How to Ask, at the very least you will need a minimal reproducible example. Nov 13, 2021 at 15:31

1 Answer 1

1

You can solve this problem by using Fibonnacci Series

Here is my code that passed all test cases

public int ClimbStairs(int n) 
{
    
        //FIBONACCI SOLUTION

        // base cases
        if (n <= 0) return 0;
        if (n == 1) return 1;
        if (n == 2) return 2;

        int one = 2;
        int two = 1;
        int temp = 0;

        for (int i = 2; i < n; i++)
        {
            temp = one + two;
            two = one;
            one = temp;
        }
        return temp;
    
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.