题目:
有个小孩正在上楼梯,楼梯有n阶台阶,小孩一次可以上1阶、2阶、3阶。请实现一个方法,计算小孩有多少种上楼的方式。为了防止溢出,请将结果Mod 1000000007
给定一个正整数int n,请返回一个数,代表上楼的方式数。保证n小于等于100000。
源码:
import java.util.*;
public class GoUpstairs {
public int countWays(int n) {
if (n == 1) {
return 1;
}
if (n == 2) {
return 2;
}
if (n == 3) {
return 4;
}
int res = 0;
int first = 1;
int second = 2;
int third = 4;
for (int i = 4; i <= n; i++) {
res = (first + second) % 1000000007 + third % 1000000007;
first = second % 1000000007;
second = third % 1000000007;
third = res;
}
return res % 1000000007;
}
}