一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。
答案需要取模 1e9 7(1000000007),如计算初始结果为:1000000008,请返回 1。
示例 1:
输入:n = 2
输出:2
示例 2:
输入:n = 7
输出:21
示例 3:
输入:n = 0
输出:1
2、C
class Solution {
public:
int numWays(int n) {
int total = 0;
if (n < 0) {
total = -1;
}
else if (n == 0 || n == 1) {
total = 1;
}
else if (n == 2) {
total = 2;
}
else {
int num1st = 1;
int num2nd = 2;
for (size_t i = 3; i <= n; i ) {
total = (num1st num2nd) % 1000000007;
num1st = num2nd;
num2nd = total;
}
}
return total;
}
};
3、Python
# 2020-9-6 DuYong
class Solution:
def numWays(self, n: int) -> int:
self.total = 0
if n < 0:
self.total = -1
elif (n == 0) or (n == 1):
self.total = 1
elif n == 2:
self.total = 2
else:
self.num1st = 1
self.num2nd = 2
for i in range(3, n 1):
self.total = (self.num1st self.num2nd) % 1000000007
self.num1st = self.num2nd
self.num2nd = self.total
return self.total
Copyright © 2024 妖气游戏网 www.17u1u.com All Rights Reserved