Suppose we have a staircase with n steps and we also have another number k, initially we are at stair 0, and we can climb up either 1, 2 or 3 steps at a time. but we can only climb 3 stairs at most k times. Now we have to find the number of ways we can climb the staircase.
So, if the input is like n = 5, k = 2, then the output will be 13, as there are different ways we can climb the stairs −
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution: def solve(self, n, k): if n==0: return 1 if n==1: return 1 k= min(k,n) memo=[*(n+1) for _ in range(k+1)] for r in range(k+1): memo[r]=1 memo[r]=1 memo[r]=2 for i in range(3,n+1): memo[i]=memo[i-1]+memo[i-2] for j in range(1,k+1): for i in range(3,n+1): count = i//3 if count<=j: memo[j][i]=memo[j][i-1]+memo[j][i-2]+memo[j][i-3] else: memo[j][i]=memo[j][i-1]+memo[j][i-2]+memo[j-1][i-3] return memo[k][n] ob = Solution() print(ob.solve(n = 5, k = 2))