一只青蛙一次可以跳上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/
方法一:递推
青蛙想上第
我们定义初始项
时间复杂度
class Solution:
def numWays(self, n: int) -> int:
a = b = 1
for _ in range(n):
a, b = b, (a + b) % 1000000007
return a
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;
}
}
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;
}
};
func numWays(n int) int {
a, b := 1, 1
for i := 0; i < n; i++ {
a, b = b, (a+b)%1000000007
}
return a
}
/**
* @param {number} n
* @return {number}
*/
var numWays = function (n) {
let a = (b = 1);
while (n--) {
[a, b] = [b, (a + b) % (1e9 + 7)];
}
return a;
};
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;
}
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
}
}
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;
}
}