剑指 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
思路:
1. f(2)=2,一次跳两格,两次跳一格
2. f(n),第一次跳一格,接下来有f(n-1)种跳法,第一次跳两格,接下来有f(n-2)种跳法
3. f(n) = f(n-1)+f(n-2),就是斐波那契数列问题
代码:
class Solution {
public:
int numWays(int n) {
if (n == 0) return 1;
if (n <= 2) return n;
int jump1 = 1;
int jump2 = 2;
int nextJump = 0;
for (int i = 3; i <= n; ++i) {
nextJump = jump1 % static_cast<int>(1e9 + 7) + jump2 % static_cast<int>(1e9 + 7);
jump1 = jump2 % static_cast<int>(1e9 + 7);
jump2 = nextJump;
}
return nextJump % static_cast<int>(1e9 + 7);
}
};