Question: You are climbing a staircase. It takes n steps to reach the top. Each time you can either jump 1 or 2 or 3 steps. In how many total number of ways can you jump to the top?
My Explanation: Well I'm thinking of applying recursion because I can find the solution by solving similar subproblems and on that process, there will be many overlapping subproblems so I'll array data structure to save the denomination of similar subproblems so that I don't need to solve same subproblem twice. So I'm using top down DP approach.
My Doubt:
Now to build the solution, I need a base case where the program flow ends and it returns back to it's parent node(if you visualize it as a tree). So the base case what I was thinking is like when I was at the floor, at ground 0 so there will be no other ways I can reach ground 0 state, so it's the base case.
When n=0, I should return 0 or 1, that's my doubt? Well I have written the code, so the code work when I return 1, not 0 at n=0. So why I should return 1 when n=0, what's the reason behind it? Please Help!!!
My Code:
#include <iostream>
using namespace std;
int climbing_ladders_topDown(int n, int k, int dp[]){
//Base Case
if(n==0){
return 1;
}
//LookUp
if(dp[n]!=0){
return dp[n];
}
//Recursive Case
int total_num_of_ways = 0;
for(int jumps=1;jumps<=k;jumps++){
if(n-jumps>=0){
total_num_of_ways += climbing_ladders_topDown(n-jumps,k,dp);
}
}
dp[n] = total_num_of_ways;
return dp[n];
}
int main() {
int num_of_stairs = 4;
int num_of_jumbs = 3;
int dp_arr[100] = {0};
cout<<climbing_ladders_topDown(num_of_stairs,num_of_jumbs,dp_arr);
return 0;
}
Output: 7
Correct flow of Code (thanks to @appleapple):
#include <iostream>
using namespace std;
int climbing_ladders_topDown(int n, int k, int dp[]){
//Base Case
if(n==0){
return 0;
}
//LookUp
if(dp[n]!=0){
return dp[n];
}
//Recursive Case
int total_num_of_ways = 0;
for(int jumps=1;jumps<=k;jumps++){
if(n-jumps > 0){
total_num_of_ways += climbing_ladders_topDown(n-jumps,k,dp);
}
if(n-jumps == 0){ // have reach the end or ground 0, base so no more move possible in downward direction
total_num_of_ways += 1;
}
if(n-jumps < 0){ //we can't move to -ve state/underground, because it doesn't exist
total_num_of_ways += 0;
}
}
dp[n] = total_num_of_ways;
return dp[n];
}
int main() {
int num_of_stairs = 4;
int num_of_jumbs = 3;
int dp_arr[100] = {0};
cout<<climbing_ladders_topDown(num_of_stairs,num_of_jumbs,dp_arr);
return 0;
}