1、题目描述
一只青蛙一次可以跳上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 DuYongclass 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
![9632b1ee00f1db9b2889955613cc47f5.png](https://i-blog.csdnimg.cn/blog_migrate/f4f7d6156bb1d01cb9c9fe6afd5401e7.jpeg)