给定距离N 。的任务是计数的方法来覆盖1,2和3步的距离的总数。
例子:
Input: N = 3
Output: 4
All the required ways are (1 + 1 + 1), (1 + 2), (2 + 1) and (3).
Input: N = 4
Output: 7
方法:在上一篇文章中,讨论了基于递归和动态编程的方法。在这里,我们将降低空间复杂度。可以肯定的是,要计算覆盖距离i的步数,只需要最后三个状态( i – 1 , i – 2 , i – 3 )。因此,可以使用最后三个状态计算结果。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the count of the
// total number of ways to cover the
// distance with 1, 2 and 3 steps
int countWays(int n)
{
// Base conditions
if (n == 0)
return 1;
if (n <= 2)
return n;
// To store the last three stages
int f0 = 1, f1 = 1, f2 = 2, ans;
// Find the numbers of steps required
// to reach the distance i
for (int i = 3; i <= n; i++) {
ans = f0 + f1 + f2;
f0 = f1;
f1 = f2;
f2 = ans;
}
// Return the required answer
return ans;
}
// Driver code
int main()
{
int n = 4;
cout << countWays(n);
return 0;
}
Java
// Java implementation of the approach
import java.io.*;
class GFG
{
// Function to return the count of the
// total number of ways to cover the
// distance with 1, 2 and 3 steps
static int countWays(int n)
{
// Base conditions
if (n == 0)
return 1;
if (n <= 2)
return n;
// To store the last three stages
int f0 = 1, f1 = 1, f2 = 2;
int ans=0;
// Find the numbers of steps required
// to reach the distance i
for (int i = 3; i <= n; i++)
{
ans = f0 + f1 + f2;
f0 = f1;
f1 = f2;
f2 = ans;
}
// Return the required answer
return ans;
}
// Driver code
public static void main (String[] args)
{
int n = 4;
System.out.println (countWays(n));
}
}
// This code is contributed by jit_t
Python
# Python3 implementation of the approach
# Function to return the count of the
# total number of ways to cover the
# distance with 1, 2 and 3 steps
def countWays(n):
# Base conditions
if (n == 0):
return 1
if (n <= 2):
return n
# To store the last three stages
f0 = 1
f1 = 1
f2 = 2
ans = 0
# Find the numbers of steps required
# to reach the distance i
for i in range(3, n + 1):
ans = f0 + f1 + f2
f0 = f1
f1 = f2
f2 = ans
# Return the required answer
return ans
# Driver code
n = 4
print(countWays(n))
# This code is contributed by mohit kumar 29
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the count of the
// total number of ways to cover the
// distance with 1, 2 and 3 steps
static int countWays(int n)
{
// Base conditions
if (n == 0)
return 1;
if (n <= 2)
return n;
// To store the last three stages
int f0 = 1, f1 = 1, f2 = 2;
int ans = 0;
// Find the numbers of steps required
// to reach the distance i
for (int i = 3; i <= n; i++)
{
ans = f0 + f1 + f2;
f0 = f1;
f1 = f2;
f2 = ans;
}
// Return the required answer
return ans;
}
// Driver code
public static void Main(String[] args)
{
int n = 4;
Console.WriteLine (countWays(n));
}
}
// This code is contributed by PrinciRaj1992
Javascript
输出:
7
时间复杂度: O(N)
空间复杂度O(1)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。