gelita

Count Steps (1,2 or 3) with memoization

Feb 25th, 2020
384
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 0.79 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. class NSteps123 {
  5.     public static void main (String[] args) {
  6.         int input = 3;
  7.         int[] cache = new int[input+1];
  8.         Arrays.fill(cache,-1);
  9.         countSteps(cache,input);
  10.         System.out.println(countSteps(cache, input));
  11.     }
  12.     public static int countSteps(int[] cache, int num) {
  13.        
  14.         if(num < 0){
  15.             return 0;
  16.         }
  17.         if(num == 0 || num == 1){
  18.             return 1;
  19.         }
  20.         if(num == 2){
  21.             return 2;
  22.         }else{
  23.            if(cache[num] > -1){
  24.                return cache[num];
  25.            }else{
  26.                cache[num] = countSteps(cache, num-1) + countSteps(cache,num-2)+ countSteps(cache,num-3);
  27.            }
  28.        }
  29.        return cache[num];
  30.     }
  31. }
Advertisement
Add Comment
Please, Sign In to add comment