LeetCode - 70. Climbing Stairs

来源:互联网 发布:mac excel 公式不计算 编辑:程序博客网 时间:2024/05/29 13:42

求问一共有多少种方式,而且题目中也比较明确地给出了递推关系,所以考虑使用动态规划,这道题属于Sequence DP,一般这种类型的动态规划问题考虑的四个要素如下:

而对于这道题目:

state: f[i]表示前i个位置,跳到第i个位置的方案总数

function: f[i] = f[i - 1] + f[i - 2]

initialize: f[0] = 1, f[1] = 1

answer: f[n]

另外这道题目有一个可以优化的地方,如果按照上面所写的这种方式来写程序的话,那么可能会需要另外一个新的数组,再仔细进行观察的话我们发现,我们可以使用三个变量来回迭代来省去数组的使用。时间复杂度为O(n),空间复杂度为O(1),代码如下:

public class Solution {    public int climbStairs(int n) {        if(n <= 1){            return 1;        }                // Initialize        int last = 1;        int lastlast = 1;        int now = 0;                // Function        for(int i = 2; i <= n; i++){            now = last + lastlast;            lastlast = last;            last = now;        }                return last;    }}


知识点:

1. 注意Sequence DP类型问题中四要素所代表的含义

2. 多考虑在Sequence DP类型的问题中可否用多变量的迭代来省去数组的使用,以减小空间复杂度

0 0
原创粉丝点击