上台阶
有一楼梯共m级,刚开始时你在第一级,若每次只能跨上一级或者二级,要走上m级,共有多少走法?注:规定从一级到一级有0种走法。
给定一个正整数int n,请返回一个数,代表上楼的方式数。保证n小于等于100。为了防止溢出,请返回结果Mod 1000000007的值。
测试样例:
3
返回:2
Java代码
package com.algorithm;
/**
* Created by wwh on 2017/12/8.
*/
public class Main01 {
public static void main(String argc[]) {
GoUpstairs obj = new GoUpstairs();
int result = obj.countWays(50);
System.out.println(result);
}
public static class GoUpstairs {
public int countWays(int n) {
final int VALUE = 1000000007;
if(n == 1) return 0;
else if(n == 2) return 1;
else if(n == 3) return 2;
int res;
int first = 1, second = 2, ret = 0;
while(n > 3) {
ret = (first + second)%VALUE;
first = second;
second = ret;
n--;
}
return ret;
}
}
}
python代码
class GoUpstairs:
def countWays(self, n):
res = [0, 1, 2]
while len(res) < n:
res.append(res[-1] + res[-2])
return res[n-1]%1000000007
obj = GoUpstairs()
res = obj.countWays(6)
print res
class GoUpstairs:
def countWays(self, n):
if n < 1:
return 0
res = [0, 1, 2]
if n > 3:
for i in range(3, n):
res.append((res[i - 1] + res[i - 2])%1000000007)
return res[n - 1]
if __name__ == "__main__":
maxNumStairs = 100
print("num stairs: (Results)")
for cnt in range(1, maxNumStairs):
stairs = GoUpstairs()
res = stairs.countWays(cnt)
print("%d stairs: (%d)" % (cnt, res))