所有的LeetCode题解索引,可以看这篇文章——【算法和数据结构】LeetCode题解。
??思路分析:本题可以从0阶或者1阶台阶开始,每次爬楼梯所需的花费是之前的花费dp[i]+从本层向上爬所需的cost[i]
d
p
[
i
]
+
c
o
s
t
[
i
]
dp[i]+cost[i]
dp[i]+cost[i]。可能到达第i阶台阶的情况有两种:从第i-2阶台阶一次性爬两步;从第i-1阶台阶一次性爬一步。因为要找到最小的花费,可以知道动态数组的表达式为:
d
p
[
i
]
=
m
i
n
(
d
p
[
i
?
2
]
+
c
o
s
t
[
i
?
2
]
,
d
p
[
i
?
1
]
+
c
o
s
t
[
i
?
1
]
)
dp[i] = min(dp[i-2]+cost[i-2],dp[i-1]+cost[i-1])
dp[i]=min(dp[i?2]+cost[i?2],dp[i?1]+cost[i?1])。
??程序如下:
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
vector<int> dp(cost.size() + 1); // 楼顶
dp[0] = 0;
dp[1] = 0;
for (int i = 2; i <= cost.size(); i++) {
dp[i] = min(dp[i-1] + cost[i-1], dp[i-2] + cost[i-2]);
}
return dp[cost.size()];
}
};
复杂度分析:
# include <iostream>
# include <vector>
# include <algorithm>
using namespace std;
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
vector<int> dp(cost.size() + 1); // 楼顶
dp[0] = 0;
dp[1] = 0;
for (int i = 2; i <= cost.size(); i++) {
dp[i] = min(dp[i-1] + cost[i-1], dp[i-2] + cost[i-2]);
}
return dp[cost.size()];
}
};
int main() {
vector<int> cost = { 1, 100, 1, 1, 1, 100, 1, 1, 100, 1 };
Solution s1;
int result = s1.minCostClimbingStairs(cost);
cout << result << endl;
system("pause");
return 0;
}
end