方法:递归
class Solution {
public:
int fib(int n) {
if (n < 2) return n;
return fib(n-1) + fib(n-2);
}
};
$时间复杂度O(),空间复杂度O(n)
方法:dp
class Solution {
#define maxn 31
int f[maxn];
public:
int fib(int n) {
f[0] = 0, f[1] = 1;
for (int i = 2; i <= n; ++i) {
f[i] = f[i-1] + f[i-2];
}
return f[n];
}
};
$时间复杂度O(n),空间复杂度O(n)
优化后
class Solution {
public:
int fib(int n) {
if (n < 1) return 0;
int f0 = 0, f1 = 1;
for (int i = 2; i <= n; ++i) {
int cur = f0 + f1;
f0 = f1;
f1 = cur;
}
return f1;
}
};
$时间复杂度O(n),空间复杂度O(1)
方法:完全背包(求方案数)
f[i]:表示台阶为i时,爬上台阶i的方案数。
class Solution {
#define maxn 46
int f[maxn];
public:
int climbStairs(int n) {
f[0] = 1;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= 2; ++j) {
if (i >= j) f[i] += f[i-j];
}
}
return f[n];
}
};
$时间复杂度O(n),空间复杂度O(n)
方法:dp
class Solution {
#define maxn 46
int f[maxn];
public:
int climbStairs(int n) {
f[0] = 1, f[1] = 1;
for (int i = 2; i <= n; ++i) {
f[i] = f[i-1] + f[i-2];
}
return f[n];
}
};
$时间复杂度O(n),空间复杂度O(n)
优化后
class Solution {
public:
int fib(int n) {
if (n < 1) return 0;
int f0 = 0, f1 = 1;
for (int i = 2; i <= n; ++i) {
int cur = f0 + f1;
f0 = f1;
f1 = cur;
}
return f1;
}
};
$时间复杂度O(n),空间复杂度O(1)
方法:递归+记忆化搜索
class Solution {
#define maxn 46
int vis[maxn];
public:
int climbStairs(int n) {
if (n == 0 || n == 1) {
vis[n] = 1;
return vis[n];
}
if (vis[n] != 0) return vis[n];
vis[n] = climbStairs(n-1) + climbStairs(n-2);
return vis[n];
}
};
$时间复杂度O(),空间复杂度O(n)
方法:dp
class Solution {
#define maxn 1010
int f[maxn];
public:
int minCostClimbingStairs(vector<int>& cost) {
int n = cost.size();
f[0] = cost[0], f[1] = cost[1];
for (int i = 2; i < cost.size(); ++i) {
f[i] = min(f[i-1], f[i-2]) + cost[i];
}
return min(f[n-1], f[n-2]);
}
};
$时间复杂度O(n),空间复杂度O(n)
优化后
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
int n = cost.size();
int f1 = 0, f2 = 0;
for (int i = 2; i <= n; ++i) {
int ff = min(f1 + cost[i-2], f2 + cost[i-1]);
f1 = f2;
f2 = ff;
}
return f2;
}
};
$时间复杂度O(n),空间复杂度O(1)