爬楼梯到达顶部

85 阅读6分钟

爬楼梯到达顶部

有 n 个楼梯,一个人站在最下面,想要爬楼梯到达第 n 个楼梯。一次可以爬 1 级楼梯或 2 级楼梯,任务是计算一个人可以到达顶部的方式。

考虑图中所示的示例。 n 的值为 3。有 3 种方法到达顶部。

nth-stair.png

例子:

输入:n = 1
输出:1
爬 1 级楼梯只有一种方法

输入:n=2
输出:2
有两种方式:(1, 1) 和 (2)

输入:n = 4
输出:5
(1, 1, 1, 1), (1, 1, 2), (2, 1, 1), (1, 2, 1), (2, 2)

使用递归:

我们很容易发现上述问题的递归本质。该人可以从第 (n-1) 个楼梯或从第 (n-2) 个楼梯到达第 n 个楼梯。因此,对于每个楼梯 n,我们尝试找出到达第 n-1 楼梯和第 n-2 楼梯的方法数,并将它们相加以给出第 n 楼梯的答案。因此,这种方法的递归关系为:

ways(n) = ways(n-1) + ways(n-2)

  • ways(1) = 1
  • ways(2) = 2

下面是上述方法的实现:

C++

// C++ program to count number of
// ways to reach Nth stair
#include <bits/stdc++.h>
using namespace std;

// A simple recursive program to
// find N'th fibonacci number
int fib(int n)
{
    if (n <= 1)
        return n;
    return fib(n - 1) + fib(n - 2);
}

// Returns number of ways to
// reach s'th stair
int countWays(int s) { return fib(s + 1); }

// Driver Code
int main()
{
    int s = 4;

    cout << "Number of ways = " << countWays(s);

    return 0;
}

C

// C Program to count number of
// ways to reach Nth stair
#include <stdio.h>

// A simple recursive program to
// find n'th fibonacci number
int fib(int n)
{
    if (n <= 1)
        return n;
    return fib(n - 1) + fib(n - 2);
}

// Returns number of ways to reach s'th stair
int countWays(int s) { return fib(s + 1); }

// Driver program to test above functions
int main()
{
    int s = 4;
    printf("Number of ways = %d", countWays(s));
    getchar();
    return 0;
}

Java

class stairs {
    // A simple recursive program to find
    // n'th fibonacci number
    static int fib(int n)
    {
        if (n <= 1)
            return n;
        return fib(n - 1) + fib(n - 2);
    }

    // Returns number of ways to reach s'th stair
    static int countWays(int s) { return fib(s + 1); }

    /* Driver program to test above function */
    public static void main(String args[])
    {
        int s = 4;
        System.out.println("Number of ways = "
                           + countWays(s));
    }

Python

# Python program to count
# ways to reach nth stair

# Recursive function to find
# Nth fibonacci number


def fib(n):
    if n <= 1:
        return n
    return fib(n-1) + fib(n-2)

# Returns no. of ways to
# reach sth stair


def countWays(s):
    return fib(s + 1)


# Driver program
s = 4
print "Number of ways = ",
print countWays(s)

C

// C# program to count the
// number of ways to reach
// n'th stair
using System;

class GFG {
    // A simple recursive
    // program to find n'th
    // fibonacci number
    static int fib(int n)
    {
        if (n <= 1)
            return n;
        return fib(n - 1) + fib(n - 2);
    }

    // Returns number of ways
    // to reach s'th stair
    static int countWays(int s) { return fib(s + 1); }

    // Driver Code
    static public void Main()
    {
        int s = 4;
        Console.WriteLine("Number of ways = "
                          + countWays(s));
    }
}

Javascript

<script>
// A Javascript program to count
// number of ways to reach
// n'th stair when a person
// can climb 1, 2, ..m stairs
// at a time.

// A simple recursive
// function to find n'th
// fibonacci number
function fib(n)
{
if (n <= 1)
    return n;
return fib(n - 1) +
       fib(n - 2);
}

// Returns number of
// ways to reach s'th stair
function countWays(s)
{
    return fib(s + 1);
}

// Driver Code
let s = 4;
document.write("Number of ways = " + countWays(s));

</script>

PHP

<?php
// A PHP program to count
// number of ways to reach
// n'th stair when a person
// can climb 1, 2, ..m stairs
// at a time.

// A simple recursive
// function to find n'th
// fibonacci number
function fib($n)
{
if ($n <= 1)
    return $n;
return fib($n - 1) +
       fib($n - 2);
}

// Returns number of
// ways to reach s'th stair
function countWays($s)
{
    return fib($s + 1);
}

// Driver Code
$s = 4;
echo "Number of ways = ",
           countWays($s);

// by m_kit
?>

输出

Number of ways = 5

时间复杂度: O(2^n) ,因为每个楼梯有两个选择,总共有 n 个楼梯。 辅助空间:O(n),因为递归堆栈空间。

使用动态规划爬楼梯(制表):

使用以下关系以自下而上的方式创建表 dp[]:

dp[i] = dp[i-1] + dp[i-2]

请按照以下步骤实施该想法:

  • 创建一个一维 dp,其中 dp[i] 表示从底部到达第 i 楼梯的方式数。
  • 初始化 dp[0] = 1,因为 n = 0 只有一种方式,dp[1] = 2,因为输入 n = 2 只有 2 种方式。
  • 现在对于每个 i >= 2,dp[i] = dp[i-1]+dp[i-2]

下面的代码实现了上述方法:

C++

// C++ program to count number of ways
// to reach n'th stair when a person
// can climb 1, 2, ..m stairs at a time
#include <iostream>
using namespace std;
// A function to find number of ways to reach the nth stair
int countWays(int n)
{
    int dp[n + 1];
    dp[0] = 1;
    dp[1] = 1;

    for (int i = 2; i <= n; i++)
        dp[i] = dp[i - 1] + dp[i - 2];
    return dp[n];
}

// Driver code
int main()
{
    int n = 4;

    cout << "Number of ways = " << countWays(n);

    return 0;
}

Java

// Java program to count number of ways
// to reach n't stair when a person
// can climb 1, 2, ..m stairs at a time

class GFG {
    // A function to find number of ways to reach the nth
    // stair
    static int countWays(int n)
    {
        int dp[] = new int[n + 1];
        dp[0] = 1;
        dp[1] = 1;

        for (int i = 2; i <= n; i++)
            dp[i] = dp[i - 1] + dp[i - 2];
        return dp[n];
    }

    // Driver method
    public static void main(String[] args)
    {
        int n = 4;
        System.out.println("Number of ways = "
                           + countWays(n));
    }
}

Python

# A program to count the number of
# ways to reach n'th stair

# A function to find number of ways to reach the nth stair


def countWays(n):
    # Creates list res with all elements 0
    dp = [0 for x in range(n+1)]
    dp[0], dp[1] = 1, 1

    for i in range(2, n+1):
        dp[i] = dp[i-1]+dp[i-2]
    return dp[n]


# Driver Program
n = 4
print "Number of ways =", countWays(n)

C

// C# program to count number
// of ways to reach n'th stair when
// a person can climb 1, 2, ..m
// stairs at a time
using System;
class GFG {

    // A function to find number of ways to reach the nth
    // stair
    static int countWays(int n)
    {
        int[] dp = new int[n + 1];
        dp[0] = 1;
        dp[1] = 1;

        for (int i = 2; i <= n; i++)
            dp[i] = dp[i - 1] + dp[i - 2];
        return dp[n];
    }

    // Driver Code
    public static void Main()
    {
        int n = 4;
        Console.WriteLine("Number of ways = "
                          + countWays(n));
    }
}

Javascript

// A function to find number of ways to reach the nth stair

function countWays(n)
{
    let dp = [];
    dp[0] = 1;
    dp[1] = 1;
    for (let i = 2; i <=n; i++)
    {
        dp[i]=dp[i-1]+dp[i-2];
    }
    return dp[n];
}


    // Driver Code
    let n=4;
    console.log("Number of ways = " + countWays(n));

输出

Number of ways = 5


时间复杂度:O(n) 辅助空间:O(n)

空间优化:

在上述方法中可以看出 dp[i] 仅取决于先前的状态。我们可以通过仅使用两个变量 prev1 和 prev2 来跟踪 dp[i-1] 和 dp[i-2] 的前两个值,将动态规划解决方案的空间复杂度优化为 O(1)。由于我们只需要这两个值来计算下一个值,因此不需要存储整个数组。

下面是上述思想的代码实现:

C++

// C++ program to count the number of ways to reach at top
// When a person climbing on stairs

#include <bits/stdc++.h>
#include <iostream>
using namespace std;

int countWays(int n)
{
    // declaring  two variables to store the count
    int prev = 1;
    int prev2 = 1;
    // Running for loop to count all possible ways
    for (int i = 2; i <= n; i++) {
        int curr = prev + prev2;
        prev2 = prev;
        prev = curr;
    }
    return prev;
}
int main()
{
    int n = 4;

    cout << "Number of Ways : " << countWays(n);

    return 0;
}

Java

// Java program to count the number of ways to reach at top
// When a person climbing on stairs

public class Solution {

    static int countWays(int n)
    {
        // declaring  two variables to store the count
        int prev = 1;
        int prev2 = 1;
        // Running for loop to count all possible ways
        for (int i = 2; i <= n; i++) {
            int curr = prev + prev2;
            prev2 = prev;
            prev = curr;
        }
        return prev;
    }
    public static void main(String[] args)
    {
        int n = 4;
        System.out.println("Number of Ways : "
                           + countWays(n));
    }
}

Python

# Python program to count the number of ways to reach at top
# When a person climbing on stairs


def countWays(n):
    # declaring  two variables to store the count
    prev = 1
    prev2 = 1
    # Running for loop to count all possible ways
    for i in range(2, n+1):
        curr = prev + prev2
        prev2 = prev
        prev = curr
    return prev


n = 4
print("Number of Ways : ", countWays(n))

C

// C# program to count the number of ways to reach at top
// When a person climbing on stairs
using System;

public class GFG {

    public static int countWays(int n)
    {
        // declaring  two variables to store the count
        int prev = 1;
        int prev2 = 1;
        // Running for loop to count all possible ways
        for (int i = 2; i <= n; i++) {
            int curr = prev + prev2;
            prev2 = prev;
            prev = curr;
        }
        return prev;
    }
    public static void Main(string[] args)
    {
        int n = 4;
        Console.WriteLine("Number of Ways : "
                          + countWays(n));
    }
}

Javascript

// JavaScript program to count the number of ways to reach at top
// When a person climbing on stairs

function countWays(n) {
    // declaring  two variables to store the count
    let prev = 1;
    let prev2 = 1;
    // Running for loop to count all possible ways
    for (let i = 2; i <= n; i++) {
        let curr = prev + prev2;
        prev2 = prev;
        prev = curr;
    }
    return prev;
}

let n = 4;
document.write("Number of Ways: ", countWays(n));

输出

Number of Ways : 5

时间复杂度:O(N) 辅助空间:O(1)