题目:
有个小孩正在上楼梯,楼梯有n阶台阶,小孩一次可以上1阶、2阶、3阶。请实现一个方法,计算小孩有多少种上楼的方式。为了防止溢出,请将结果Mod 1000000007
给定一个正整数int n,请返回一个数,代表上楼的方式数。保证n小于等于100000。
测试样例:
1
返回:1
class GoUpstairs {
public:
int countWays(int n) {
// write code here
int res = 0;
if(n<1) return 0;
if(n == 1) return 1;
if(n == 2) return 2;
if(n == 3) return 4;
int pre1 = 1;
int pre2 = 2;
int pre3 = 4;
for(int i = 4; i <= n; i++){
res = ((pre3+pre2)%1000000007+pre1)%1000000007; //关键在这里 取模运算有这样一个性质:(a+b)%c = ((a%c)+(b%c))%c
//所以(pre3+pre2)%1000000007就相当于(pre3%X+pre2%X)%X 用X代替1000000007
//这样就使得pre3、pre2、pre3+pre2都没有溢出,之后再与pre1相加之后取模,使得全部结果没有溢出。
pre1 = pre2; pre2 = pre3; pre3 = res;
}
return res;
}
};
关键在这里 取模运算有这样一个性质:(a+b)%c = ((a%c)+(b%c))%c
所以(pre3+pre2)%1000000007就相当于(pre3%X+pre2%X)%X 用X代替1000000007
这样就使得pre3、pre2、pre3+pre2都没有溢出,之后再与pre1相加之后取模,使得全部结果没有溢出。