题目描述
Mr. Strong一步最多可以登上4阶楼梯;请编程求解 Mr. Strong一共有多少种方法登上阶梯数为 n 的楼梯?
输入
输入整数n, 1 =< n <= 20000;
输出
Mr. Strong登梯方式的总数
样例输入
4
样例输出
8
提示
如果登上5级楼梯,Mr. Strong 可以有以下 15 种攀登方式(每一行代表一种攀登方式,一行中的整数 代表 每一步依次登梯的级数):
1 1 1 1 1
1 1 1 2
1 1 2 1
1 1 3
1 2 1 1
1 2 2
1 3 1
1 4
2 1 1 1
2 1 2
2 2 1
2 3
3 1 1
3 2
4 1
请考虑: 登上n级楼梯的方法数 与 登上n-1, n-2, n-3, n-4级楼梯的方法数 之间的关系?
类似斐波那契数列
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
if(1<=n && n<=20000) {
System.out.print(f(n));
}
}
public static BigInteger f(int n) {
BigInteger a = BigInteger.valueOf(1);
BigInteger b = BigInteger.valueOf(2);
BigInteger c = BigInteger.valueOf(4);
BigInteger d = BigInteger.valueOf(8);
BigInteger sum = BigInteger.valueOf(0);
if(n == 1) return a;
if(n == 2) return b;
if(n == 3) return c;
if(n == 4) return d;
else {
for(int i=5;i<=n;i++) {
sum = a.add(b).add(c).add(d);
a = b;
b = c;
c = d;
d = sum;
}
return sum;
}
}
}