Advertisement
Fastrail08

Climbing Stairs

May 19th, 2025
403
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.14 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. //Question - Count the number of paths from nth Stair to 0th Stair
  5.  
  6.  
  7. // Another way of thinking is to break it down into levels and options
  8. // Levels - Each Stair
  9. // Options - 3 possible jumps from each stair
  10.  
  11. // Recursive code + memo
  12. int countStairPath(int n, vector<int> &memo){
  13.     // base case
  14.     if(n == 0){
  15.         return 1;
  16.     }
  17.    
  18.     //invalid case
  19.     if(n < 0){
  20.         return 0;
  21.     }
  22.    
  23.     //memo check
  24.     if(memo[n] != 0){
  25.         return memo[n];
  26.     }
  27.     //paths from n - 1
  28.     int pathsNm1 = countStairPath(n - 1, memo);
  29.     //path from n - 2
  30.     int pathsNm2 = countStairPath(n - 2, memo);
  31.     //path from n - 3
  32.     int pathsNm3 = countStairPath(n - 3, memo);
  33.    
  34.    
  35.     return memo[n] = pathsNm1 + pathsNm2 + pathsNm3;
  36. }
  37.  
  38.  
  39. //dp code
  40. int getStairPath(int n){
  41.     // dp array (as we need the answer for n, so N + 1 size required)
  42.     vector<int> dp(n + 1);
  43.    
  44.     /*
  45.     1) MEANING
  46.     dp[n] = total number of paths from n to 0th stair
  47.     generally each cell will answer the same question but with smaller param
  48.     Each cell holds the answer to all the possible unique recursive states
  49.  
  50.     2) DIRECTION
  51.     smaller problem is at dp[0]
  52.     dp[0] - stores answer for all the paths from 0th stair to 0th stair = 1
  53.     so direction to solve would be from smaller problem to larger problem 0 -> n
  54.    
  55.     3) TRAVEL & SOLVE
  56.     loop in the direction
  57.     */
  58.    
  59.     // ASSIGN VALUE TO BASE CASE as we did in memo code
  60.     dp[0] = 1;
  61.     for(int i = 1; i <= n; i++){
  62.         if(i == 1){
  63.             dp[i] = dp[i - 1];
  64.         }
  65.         else if(i == 2){
  66.             dp[i] = dp[i - 1] + dp[i - 2];
  67.         }
  68.         // to figure out to which dp[i] is related just see the recursion tree, and watch which state is calling which states to get the answer.
  69.         else{
  70.             dp[i] = dp[i - 3] + dp[i - 2] + dp[i - 1];
  71.         }
  72.     }
  73.     return dp[n];
  74. }
  75.  
  76. int main() {
  77.     // your code goes here
  78.     int n;
  79.     cin >> n;
  80.     vector<int> memo(n + 1, 0);
  81.     //cout << countStairPath(n, memo) << '\n';
  82.     cout << getStairPath(n) << '\n';
  83. }
  84.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement