LeetCode每日一题: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?

问题分析

爬梯子和青蛙跳是递归中很经典的题目,但是这道题目直接递归的话会超时,所以只能用动态规划做。
设dp[i]表示跳n步的方法数,那么可以往前推一次,可以由dp[i-2]跳两步或者是dp[i-1]跳一步过来

  • dp[i]=dp[i-2]+dp[i-1];

代码实现

public int climbStairs(int n) {
        int[] dp = new int[n + 1];
        if (n == 1) return 1;
        if (n == 2) return 2;
        dp[0] = 0;
        dp[1] = 1;
        dp[2] = 2;
        for (int i = 3; i <= n; i++) {
            dp[i] = dp[i - 2] + dp[i - 1];
        }
        return dp[n];
    }

你可能感兴趣的:(LeetCode每日一题:climbing stairs)