Skip to content

Latest commit

 

History

History
200 lines (155 loc) · 3.79 KB

File metadata and controls

200 lines (155 loc) · 3.79 KB
comments difficulty edit_url
true
简单

题目描述

一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。

答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。

示例 1:

输入:n = 2
输出:2

示例 2:

输入:n = 7
输出:21

示例 3:

输入:n = 0
输出:1

提示:

  • 0 <= n <= 100

注意:本题与主站 70 题相同:https://leetcode.cn/problems/climbing-stairs/

 

解法

方法一:递推

青蛙想上第 $n$ 级台阶,可从第 $n-1$ 级台阶跳一级上去,也可从第 $n-2$ 级台阶跳两级上去,即 $f(n) = f(n-1) + f(n-2)$。这实际上可以转换为斐波那契数列的问题。

我们定义初始项 $a=1$, $b=1$,接下来执行 $n$ 次循环,每次循环中,计算 $c=a+b$,并更新 $a=b$, $b=c$,循环 $n$ 次后,答案即为 $a$

时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为输入的整数。

Python3

class Solution:
    def numWays(self, n: int) -> int:
        a = b = 1
        for _ in range(n):
            a, b = b, (a + b) % 1000000007
        return a

Java

class Solution {
    public int numWays(int n) {
        int a = 1, b = 1;
        while (n-- > 0) {
            int c = (a + b) % 1000000007;
            a = b;
            b = c;
        }
        return a;
    }
}

C++

class Solution {
public:
    int numWays(int n) {
        int a = 1, b = 1;
        while (n--) {
            int c = (a + b) % 1000000007;
            a = b;
            b = c;
        }
        return a;
    }
};

Go

func numWays(n int) int {
	a, b := 1, 1
	for i := 0; i < n; i++ {
		a, b = b, (a+b)%1000000007
	}
	return a
}

TypeScript

function numWays(n: number): number {
    let a = 0;
    let b = 1;
    for (let i = 0; i < n; i++) {
        [a, b] = [b, (a + b) % 1000000007];
    }
    return b;
}

Rust

impl Solution {
    pub fn num_ways(n: i32) -> i32 {
        let mut tup = (0, 1);
        for _ in 0..n {
            tup = (tup.1, (tup.0 + tup.1) % 1000000007);
        }
        tup.1
    }
}

JavaScript

/**
 * @param {number} n
 * @return {number}
 */
var numWays = function (n) {
    let a = (b = 1);
    while (n--) {
        [a, b] = [b, (a + b) % (1e9 + 7)];
    }
    return a;
};

C#

public class Solution {
    public int NumWays(int n) {
        int a = 1, b = 1, tmp;
        for (int i = 0; i < n; i++) {
            tmp = a;
            a = b;
            b = (tmp + b) % 1000000007;
        }
        return a % 1000000007;
    }
}

Swift

class Solution {
    func numWays(_ n: Int) -> Int {
        var a = 1
        var b = 1
        var count = n
        while count > 0 {
            let c = (a + b) % 1000000007
            a = b
            b = c
            count -= 1
        }
        return a
    }
}