My recursion solution using array to avoid reduplicate calculation and time limitation


  • -1
    N

    Blockquote
    array stored the result of the same i .

    public class Solution {
    public int climbStairs(int n
    ) {
    int[] a= new int[128];
    for (int i=0;i<a.length; i++) {
    a[i]=0;
    }
    return helper(n, a);
    }

    int helper(int i, int[] a) {
        if (i == 0)
        return 0;
        if (i == 1)
        return 1;
        if(i==2)
        return 2;
        if(i>2){
            if (a[i]!= 0) {
            return a[i];
    

    }
    else {

       a[i]= helper(i-1,a) + helper(i-2,a);
       return a[i];
            }
        }
        return 0;
    }
    

    }


Log in to reply
 

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