Advertisement
Fastrail08

Climbing Stairs Variable Jumps

May 19th, 2025
497
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.10 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. /*
  5. QUESTION - Count all the ways to reach nth stair from 0th stair
  6. */
  7.  
  8. int variableJumpStairs(int stair, int &n, vector<int> &jumps, int &count, vector<int> &memo){
  9.     //invalid case
  10.     if(stair > n){
  11.         return 0;
  12.     }
  13.    
  14.     // base case
  15.     if(stair == n){
  16.         count++;
  17.         return 1;
  18.     }
  19.     //memo check
  20.     if(memo[stair] != 0){
  21.         return memo[stair];
  22.     }
  23.     //level - each stair
  24.     // options - jumps available from each stair
  25.     int allPathsFromCurrStair = 0;
  26.     for(int i = 1; i <= jumps[stair]; i++){
  27.         allPathsFromCurrStair += variableJumpStairs(stair + i, n, jumps, count, memo);
  28.     }
  29.     return memo[stair] = allPathsFromCurrStair;
  30. }
  31.  
  32. int variableJumpStairsDP(int &n, vector<int> &jumps){
  33.     //1. Storage & Meaning - dp[i] = how many ways to reach nth stair from ith stair
  34.     vector<int> dp(n + 1, 0);
  35.    
  36.     //2. Direction - We need to reach nth from 0th,smaller problem will be when we are standing at nth stair,
  37.     //count the number of ways to reach nth stair when you are standing at nth stair = 1
  38.     // largest problem = dp[0] ; smallest problem = dp[n + 1]
  39.     dp[n] = 1;
  40.    
  41.     //3. Travel & Solve - Travel in the direction of small problem to large problem & return the original largest problem
  42.     //Here at dp[0] and not at dp[n + 1].
  43.     for(int i = n - 1; i >= 0; i--){
  44.         for(int j = 1; j <= jumps[i]; j++){
  45.             if(i + j <= n + 1){
  46.                 dp[i] += dp[i + j];
  47.             }
  48.         }
  49.     }
  50.     return dp[0];
  51. }
  52.  
  53. int main() {
  54.     // your code goes here
  55.     int n;
  56.     cin >> n;
  57.     vector<int> jumps(n);
  58.     for(int i = 0; i < n; i++){
  59.         cin >> jumps[i];
  60.     }
  61.     int count = 0;
  62.     vector<int> memo(n + 1, 0);
  63.     //memo call(return method)
  64.     cout << variableJumpStairs(0, n, jumps, count, memo) << '\n';
  65.    
  66.     //memo call (print method) it will not work now, as we are not reaching base case everytime because of memo check
  67.     // cout << count << '\n';
  68.    
  69.     //dp call
  70.     cout << variableJumpStairsDP(n, jumps) << '\n';
  71. }
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement