LeetCode-70-Climbing Stairs(爬楼梯)

Q:

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?

Note: Given n will be a positive integer.

Analysis:

经典的动态规划问题。一阶台阶只可能有1种方法,即只上一层台阶;二层台阶可以有2种方法,即一次上一阶台阶上两次或者一次上两阶台阶;依次类推。

公式为:dp[i]=dp[i-1]+dp[i-2]

Code:

public class Solution {
    public int climbStairs(int n) {
        if (n <= 2) {
            return n;
        } else {
            int []ways=new int[n];
            ways[0]=1;
            ways[1]=2;
            for(int i=2;i<n;i++){
                ways[i]=ways[i-1]+ways[i-2];
            }
            return ways[n-1];
        }
    }
}

猜你喜欢

转载自blog.csdn.net/renxingkai/article/details/76656176