`
jlj008
  • 浏览: 95156 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

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

 
阅读更多
问题大致是这样的: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));
	}
	
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics