一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。
答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请
返回 1。
写法一:递归
public int numWays(int n) {
if (n <= 1) {
return 1;
}
int[] dp = new int[n];
dp[0] = 1;
dp[1] = 2;
for (int i = 2; i < n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
dp[i] %= 1000000007;
}
// 返回最后一个下标对应的数==dp[dp.length-1];
return dp[dp.length - 1];
}
写法二:迭代的做法:
static public int numWays2(int n) {
if (n <= 1) {
return 1;
}
int a = 1, b = 2;
for (int i = 3; i <= n; i++) {
int sum = (a + b) % 1000000007;
a = b;
b = sum;
}
return b;
}
static public int numWays3(int n) {
int a = 1, b = 1, sum = 0;
for (int i = 0; i < n; i++) {
sum = (a + b) % 1000000007;
a = b;
b = sum;
}
return a;
}
}
end.