Count number of ways to cover a distance | Set 2
Last Updated :
29 Mar, 2022
Given a distance N. The task is to count the total number of ways to cover the distance with 1, 2 and 3 steps.
Examples:
Input: N = 3
Output: 4
All the required ways are (1 + 1 + 1), (1 + 2), (2 + 1) and (3).
Input: N = 4
Output: 7
Approach: In previous article, a recursive and dynamic programming based approach has been discussed. Here we will reduce the space complexity. It can be observed that to calculate the number of steps to cover the distance i, only the last three states are required (i – 1, i – 2, i – 3). So, the result can be calculated using the last three states.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int countWays( int n)
{
if (n == 0)
return 1;
if (n <= 2)
return n;
int f0 = 1, f1 = 1, f2 = 2, ans;
for ( int i = 3; i <= n; i++) {
ans = f0 + f1 + f2;
f0 = f1;
f1 = f2;
f2 = ans;
}
return ans;
}
int main()
{
int n = 4;
cout << countWays(n);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int countWays( int n)
{
if (n == 0 )
return 1 ;
if (n <= 2 )
return n;
int f0 = 1 , f1 = 1 , f2 = 2 ;
int ans= 0 ;
for ( int i = 3 ; i <= n; i++)
{
ans = f0 + f1 + f2;
f0 = f1;
f1 = f2;
f2 = ans;
}
return ans;
}
public static void main (String[] args)
{
int n = 4 ;
System.out.println (countWays(n));
}
}
|
Python
def countWays(n):
if (n = = 0 ):
return 1
if (n < = 2 ):
return n
f0 = 1
f1 = 1
f2 = 2
ans = 0
for i in range ( 3 , n + 1 ):
ans = f0 + f1 + f2
f0 = f1
f1 = f2
f2 = ans
return ans
n = 4
print (countWays(n))
|
C#
using System;
class GFG
{
static int countWays( int n)
{
if (n == 0)
return 1;
if (n <= 2)
return n;
int f0 = 1, f1 = 1, f2 = 2;
int ans = 0;
for ( int i = 3; i <= n; i++)
{
ans = f0 + f1 + f2;
f0 = f1;
f1 = f2;
f2 = ans;
}
return ans;
}
public static void Main(String[] args)
{
int n = 4;
Console.WriteLine (countWays(n));
}
}
|
Javascript
<script>
function countWays(n)
{
if (n == 0)
return 1;
if (n <= 2)
return n;
let f0 = 1, f1 = 1, f2 = 2;
let ans = 0;
for (let i = 3; i <= n; i++)
{
ans = f0 + f1 + f2;
f0 = f1;
f1 = f2;
f2 = ans;
}
return ans;
}
let n = 4;
document.write(countWays(n));
</script>
|
Time Complexity: O(N)
Space Complexity O(1)
Share your thoughts in the comments
Please Login to comment...