(Java)LeetCode-70. Climbing Stairs

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?


这道题是一个比较经典比较简单的问题。

每次可以爬一阶或两阶台阶,求爬n阶台阶有多少种爬法f(n) 其实是一个简单的动态规划问题,因为f(n)= f(n-1) + f(n-2) 

注意保留已经计算过的f(n),要不然效率会很低。代码如下:


public class Solution {
    public int climbStairs(int n) {
        int[] flags = new int[n+1];
        for(int i = 0; i <= n; i++){
        	flags[i] = -1;
        }
        return climbStairs(flags,n);
    }

	private int climbStairs(int[] flags, int n) {
		// TODO Auto-generated method stub
		if(flags[n] != -1){
			return flags[n];
		}
		if(n == 1 || n == 0){
			flags[n] = 1;
			return 1;
		}else{
			flags[n] = climbStairs(flags,n-1) + climbStairs(flags,n-2);
			return flags[n];
		}
	}
}


你可能感兴趣的:(LeetCode,JAVA,Dynamic,Programming)