爬楼梯上台阶可能性的算法

问题大致是这样的:50格楼梯,每次可以上1个或2个台阶,问爬完楼梯方法的可能性有几种。
答:简单的递归可以算出,但是时间复杂度是指数级的;好的做法是可以在递归中,把中间结果缓存起来,这样可以避免递归中的重复计算,提高了运算速度,该算法复杂度是线性级的o(n)。


/*
* There are a certain number of steps of a stair, one can be up stair
* by 1 step or 2 steps for each time. How many possibilities one can
* go up stairs?
*
* Answer, if only using recursion, the time complex is index grade while
* catching each middle result changes it to linear grade.
*/
package com.algo;

public class Stairs {

long[] results;

public long calculateApproaches(int stairCount) { // 1 - 50
if (results == null) results = new long[stairCount];

if (stairCount < 0) return 0;
if (stairCount == 0) return 1;

if (results[stairCount - 1] != 0) return results[stairCount - 1];

long temp = 0;
if (stairCount == 1) {
temp = 1;
} else {
temp = calculateApproaches(stairCount - 1) + calculateApproaches(stairCount - 2);
}

results[stairCount - 1] = temp;

return temp;
}

public static void main(String[] args) {
System.out.println("n=1 : " + new Stairs().calculateApproaches(1));
System.out.println("n=2 : " + new Stairs().calculateApproaches(2));
System.out.println("n=3 : " + new Stairs().calculateApproaches(3));
System.out.println("n=4 : " + new Stairs().calculateApproaches(4));
System.out.println("n=5 : " + new Stairs().calculateApproaches(5));
System.out.println("n=6 : " + new Stairs().calculateApproaches(6));
System.out.println("n=40 : " + new Stairs().calculateApproaches(40));
System.out.println("n=50 : " + new Stairs().calculateApproaches(50));
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值