首页 > 代码库 > [LeetCode]Climbing Stairs

[LeetCode]Climbing Stairs

题目:给定一个int型整数n,表示楼梯的阶数,走楼梯时每次可以走一步,也可以走两步,求走完n阶楼梯有多少种不同的方法

算法:递归是最简单的方法,但是会超时;递归转换为递推公式:f(n) = f(n-1)+f(n-2)

public class Solution {
    public int climbStairs(int n) {
			final int STAIRS = 50;
	        int[] nSteps = new int[STAIRS];
	        nSteps[0] = 0;
	        nSteps[1] = 1;
	        nSteps[2] = 2;
	        nSteps[3] = 3;
	        for (int i=4; i<STAIRS; ++i) {
	        	nSteps[i] = nSteps[i-1] + nSteps[i-2];
	        }
	        
	        return nSteps[n];
	    }
}