Advertisement
tsnaik

Climbing Stairs

Dec 25th, 2019
671
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.98 KB | None | 0 0
  1. class Solution {
  2.     public int climbStairs(int n) {
  3.         if(n==0 || n==1 || n==2) {
  4.             return n;
  5.         }
  6.  
  7.         int[] cache = new int[n+1];
  8.         for(int i=0; i<=2; i++) {
  9.             cache[i] = i;
  10.         }
  11.         for(int i=3; i<=n; i++) {
  12.             cache[i] = -1;
  13.         }        
  14.         return climb(n, cache)[n];
  15.     }
  16.    
  17.     private int[] climb(int n, int[] cache) {
  18.         int steps = 0;
  19.    
  20.         if(n-1 >= 0) {
  21.             if(cache[n-1] >= 0) {
  22.                 steps += cache[n-1];
  23.             } else {
  24.                 cache = climb(n - 1, cache);
  25.                 steps += cache[n-1]; // climbing one step
  26.             }
  27.         }
  28.         if(n-2 >= 0) {
  29.             if(cache[n-2] >= 0) {
  30.                 steps += cache[n-2];
  31.             } else {
  32.                 cache = climb(n - 2, cache);
  33.                 steps += cache[n-2]; // climbing two steps
  34.             }
  35.         }
  36.         cache[n] = steps;
  37.         return cache;
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement