Climbing Stairs:Time exceeded exception -Java


  • 0
    P

    Why does the time exceed after 40 in dynamic programming solution compared to iterative? Any idea?

    public class Solution {
        public int climbStairs(int n) {
            if(n==0){
                return 0;
            }
            if(n==1){
                return 1;
            }
            if(n==2){
                return 2;
            }
            return (climbStairs(n-1)+climbStairs(n-2));
        }
    }

  • 0

    Try memorization! Similar question here.


  • 0
    D

    This problem is the same thing as calculating the nth fibonacci number essentially. Doing that recursively results in an exponential running time O(2^n). For 40 that is quite large. Your solution is not DP since you are not caching the intermediate results, each of the recursive calls will do a lot of overlapping computations.


Log in to reply
 

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