leetcode 爬楼梯

题目:

假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。

有三种解决方法(本菜鸡还没想出来第四种)

递归:既耗时间,又耗空间

class Solution {
public:
unordered_map<int, int> m;
int floor(int n) {
if (n <= 2) return n;
return floor(n-1) + floor(n-2);
}
int climbStairs(int n) {
int ans = floor(n);
return ans;
}
};

迭代法:省时间省空间

class Solution {
public:
int climbStairs(int n) {
if(n == 1){return 1;}
if(n == 2){return 2;}
int a = 1, b = 2, temp;
for(int i = 3; i <= n; i++){
temp = a;
a = b;
b = temp + b;
}
return b;
}
};

递归+标记数组:以空间换时间

标记数组,减少递归重复次数_解决方法

class Solution {
public:
unordered_map<int, int> m; // 所谓的标记数组
int floor(int n) {
if (n <= 2) return n;
if (m[n] != 0) {
return m[n];
}
return m[n] = floor(n-1) + floor(n-2);
}
int climbStairs(int n) {
int ans = floor(n);
return ans;
}
};