通过跳跃 1 到 N 来计算到达第 N 级楼梯的方式数
给定一个描述楼梯数量的整数N ,任务是计算通过 1 到 N 的跳跃到达第 N个楼梯的方式的数量。
例子:
Input: N = 2
Output: 2
Explanation: Two ways to reach are: (1, 1) & (2)
Input: N = 3
Output: 4
Input: N = 4
Output: 8
方法:在这个问题中,到达第i个楼梯的路径数是:
Ways to reach ith stair = (Sum of ways to reach stairs 1 to i-1)+1
As for any stair before i, ith stair can be reached in a single jump. And +1 for jumping directly to i.
现在解决这个问题:
- 创建一个变量sum以存储到达特定楼梯的方式数。用0初始化它。
- 运行从i=1到i=N-1的循环,每次迭代:
- 创建一个变量,比如cur来存储当前楼梯的路径数。所以, cur = sum + 1 。
- 将 sum 更改为sum = sum + cur 。
- 循环结束后返回sum + 1作为此问题的答案。
下面是上述方法的实现:
C++
// C++ code for the above approach
#include
using namespace std;
// Function to count the number of ways
// to reach Nth stair
int findWays(int N)
{
int sum = 0;
for (int i = 1; i < N; i++) {
int cur = sum + 1;
sum += cur;
}
return sum + 1;
}
// Driver Code
int main()
{
int N = 10;
cout << findWays(N);
}
Java
// Java code for the above approach
import java.util.*;
public class GFG
{
// Function to count the number of ways
// to reach Nth stair
static int findWays(int N)
{
int sum = 0;
for (int i = 1; i < N; i++) {
int cur = sum + 1;
sum += cur;
}
return sum + 1;
}
// Driver Code
public static void main(String args[])
{
int N = 10;
System.out.print(findWays(N));
}
}
// This code is contributed by Samim Hossain Mondal.
Python3
# python3 code for the above approach
# Function to count the number of ways
# to reach Nth stair
def findWays(N):
sum = 0
for i in range(1, N):
cur = sum + 1
sum += cur
return sum + 1
# Driver Code
if __name__ == "__main__":
N = 10
print(findWays(N))
# This code is contributed by rakeshsahni
C#
// C# code to implement above approach
using System;
class GFG
{
// Function to count the number of ways
// to reach Nth stair
static int findWays(int N)
{
int sum = 0;
for (int i = 1; i < N; i++) {
int cur = sum + 1;
sum += cur;
}
return sum + 1;
}
// Driver code
public static void Main()
{
int N = 10;
Console.Write(findWays(N));
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
输出
512
时间复杂度: O(N)
辅助空间: O(1)