本问题对应的 leetcode 原文链接:剑指 Offer 10- II. 青蛙跳台阶问题
问题描述
一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。
答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
示例 1:
输入:n = 2
输出:2
示例 2:
输入:n = 7
输出:21
示例 3:
输入:n = 0
输出:1
限制:
0 <= n <= 100
解题思路
视频讲解直达: 本题视频讲解
代码实现
// 如果看不懂代码为啥这样写,可以参考上一题
public int numWays(int n) {
//递归公示 f(n) = f(n - 1) + f(n - 2);
if( n <= 1)
return 1;
int a = 1;
int b = 1;
int c = 0;
for(int i = 2; i <= n; i++){
c = (a + b) % 1000000007;
a = b;
b = c;
}
return c;
}
时间复杂度:O(n)
额外空间复杂度:O(1)
Python
class Solution(object):
def numWays(self, n):
"""
:type n: int
:rtype: int
"""
if n <= 1:
return 1
a, b = 1, 1
for i in range(2, n+1):
c = (a + b) % 1000000007
a = b
b = c
return c
C++
class Solution {
public:
int numWays(int n) {
if (n <= 1) {
return 1;
}
int a = 1;
int b = 1;
int c = 0;
for (int i = 2; i <= n; i++) {
c = (a + b) % 1000000007;
a = b;
b = c;
}
return c;
}
};
Go
func numWays(n int) int {
if n <= 1 {
return 1
}
a, b := 1, 1
var c int
for i := 2; i <= n; i++ {
c = (a + b) % 1000000007
a = b
b = c
}
return c
}
JS
/**
* @param {number} n
* @return {number}
*/
var numWays = function(n) {
//递归公示 f(n) = f(n - 1) + f(n - 2);
if( n <= 1){
return 1;
}
let a = 1;
let b = 1;
let c = 0;
for(let i = 2; i <= n; i++){
c = (a + b) % 1000000007;
a = b;
b = c;
}
return c;
};