LeetCode - 70. Climbing Stairs
2016-07-09 19:48
411 查看
求问一共有多少种方式,而且题目中也比较明确地给出了递推关系,所以考虑使用动态规划,这道题属于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
另外这道题目有一个可以优化的地方,如果按照上面所写的这种方式来写程序的话,那么可能会需要另外一个新的数组,再仔细进行观察的话我们发现,我们可以使用三个变量来回迭代来省去数组的使用。时间复杂度为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类型的问题中可否用多变量的迭代来省去数组的使用,以减小空间复杂度
而对于这道题目:
state: f[i]表示前i个位置,跳到第i个位置的方案总数
function: f[i] = f[i - 1] + f[i - 2]
initialize: f[0] = 1, f[1] = 1
answer: f
另外这道题目有一个可以优化的地方,如果按照上面所写的这种方式来写程序的话,那么可能会需要另外一个新的数组,再仔细进行观察的话我们发现,我们可以使用三个变量来回迭代来省去数组的使用。时间复杂度为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类型的问题中可否用多变量的迭代来省去数组的使用,以减小空间复杂度
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解