LeetCode 70. Climbing Stairs 动态规划java解题日记

什么是动态规划

Dynamic programming, like the divide-and-conquer method, solves problems by combining the solutions to subproblems.
在Introduction to algorithms中,书里提到
When developing a dynamic-programming algorithm, we follow a sequence of four steps:

  1. Characterize the structure of an optimal solution.
  2. Recursively define the value of an optimal solution.
  3. Compute the value of an optimal solution, typically in a bottom-up fashion.
  4. Construct an optimal solution from computed information.

爬楼梯问题

最开始的时候,我不懂的这个题跟斐波那契数列有什么关系,经过在纸上操作了几个例子之后发现:
因为我们每次只能爬2或者1阶楼梯,那么我们就在(n-1)和(n-2)处做文章。在(n-1)的位置上,我们再爬1阶就能到n,有多少种方法能爬到n-1,便是有多少种方法能通过只爬一阶楼梯到n。同理,在(n-2)的位置上,只要知道有多少种方法到(n-2)的位置,我们即可知道有多少种方法爬2阶楼梯到n。综上所述,爬到(n-1)的所有方法的数量+爬到(n-2)的所有的方法的数量,则为爬到n阶楼梯的方法的数量。

在这个例子中,我们发现了爬n阶楼梯的方法的数量跟爬(n-1)和(n-2)阶楼梯的数量的关系,这就是个把大问题分解成小问题的很好的例子。通过把(n-1)和(n-2)的情况combine在一起,我们conquer了这个大问题。

    public int climbStairs(int n) {
        int[] dp = new int[n + 1]; //创建DP数组
        dp[1] = 1; //爬一阶楼梯只有一种方法
        dp[2] = 2;//爬两阶楼梯有两种方法,第一阶开始爬1节,或者从第0阶开始爬2节
        for (int i = 3; i <= n; i++) {
            dp[i] = dp[i - 1] + dp[i - 2]; 
        }
        return dp[n];
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值