📌  相关文章
📜  通过跳跃 1 到 N 来计算到达第 N 级楼梯的方式数

📅  最后修改于: 2022-05-13 01:56:09.983000             🧑  作者: Mango

通过跳跃 1 到 N 来计算到达第 N 级楼梯的方式数

给定一个描述楼梯数量的整数N ,任务是计算通过 1 到 N 的跳跃到达第 N楼梯的方式的数量。

例子:

方法:在这个问题中,到达第i楼梯的路径数是:

现在解决这个问题:

  1. 创建一个变量sum以存储到达特定楼梯的方式数。用0初始化它。
  2. 运行从i=1i=N-1的循环,每次迭代:
    1. 创建一个变量,比如cur来存储当前楼梯的路径数。所以, cur = sum + 1
    2. 将 sum 更改为sum = sum + cur
  3. 循环结束后返回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)