Number of ways to reach Nth floor by taking at-most K leaps
Last Updated :
21 Jul, 2022
Given N number of stairs. Also given the number of steps that one can cover at most in one leap (K). The task is to find the number of possible ways one (only consider combinations) can climb to the top of the building in K leaps or less from the ground floor.
Examples:
Input: N = 5, K = 3
Output: 5
To reach stair no-5 we can choose following combination of leaps:
1 1 1 1 1
1 1 1 2
1 2 2
1 1 3
2 3
Therefore the answer is 5.
Input: N = 29, K = 5
Output: 603
Let combo[i] be the number of ways to reach the i-th floor. Hence the number of ways to reach combo[i] from combo[j] by taking a leap of i-j will be combo[i] += combo[j]. So iterate for all possible leaps, and for each possible leaps keep adding the possible combinations to the combo array. The final answer will be stored in combo[N].
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int solve( int N, int K)
{
int combo[N + 1] = { 0 };
combo[0] = 1;
for ( int i = 1; i <= K; i++) {
for ( int j = 0; j <= N; j++) {
if (j >= i) {
combo[j] += combo[j - i];
}
}
}
return combo[N];
}
int main()
{
int N = 29;
int K = 5;
cout << solve(N, K);
return 0;
}
|
Java
class GFG
{
static int solve( int N, int K)
{
int [] combo;
combo = new int [ 50 ];
combo[ 0 ] = 1 ;
for ( int i = 1 ; i <= K; i++)
{
for ( int j = 0 ; j <= N; j++)
{
if (j >= i)
{
combo[j] += combo[j - i];
}
}
}
return combo[N];
}
public static void main(String args[])
{
int N = 29 ;
int K = 5 ;
System.out.println(solve(N, K));
}
}
|
Python 3
def solve(N, K) :
combo = [ 0 ] * (N + 1 )
combo[ 0 ] = 1
for i in range ( 1 , K + 1 ) :
for j in range ( 0 , N + 1 ) :
if j > = i :
combo[j] + = combo[j - i]
return combo[N]
if __name__ = = "__main__" :
N, K = 29 , 5
print (solve(N, K))
|
C#
using System;
class GFG
{
static int solve( int N, int K)
{
int [] combo;
combo = new int [50];
combo[0] = 1;
for ( int i = 1; i <= K; i++)
{
for ( int j = 0; j <= N; j++)
{
if (j >= i)
{
combo[j] += combo[j - i];
}
}
}
return combo[N];
}
public static void Main()
{
int N = 29;
int K = 5;
Console.WriteLine(solve(N, K));
}
}
|
PHP
<?php
error_reporting (0);
function solve( $N , $K )
{
$combo [ $N + 1] = array ();
$combo [0] = 1;
for ( $i = 1; $i <= $K ; $i ++)
{
for ( $j = 0; $j <= $N ; $j ++)
{
if ( $j >= $i )
{
$combo [ $j ] += $combo [ $j - $i ];
}
}
}
return $combo [ $N ];
}
$N = 29;
$K = 5;
echo solve( $N , $K );
?>
|
Javascript
<script>
function solve(N, K)
{
let combo = new Array(50);
combo.fill(0);
combo[0] = 1;
for (let i = 1; i <= K; i++)
{
for (let j = 0; j <= N; j++)
{
if (j >= i)
{
combo[j] += combo[j - i];
}
}
}
return combo[N];
}
let N = 29;
let K = 5;
document.write(solve(N, K));
</script>
|
Time Complexity: O(N*K)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...