cpp-algo-cases/chapter_dynamic_programming/min_cost_climbing_stairs_dp...

54 lines
1.3 KiB
C++
Raw Normal View History

2024-02-20 16:13:23 +08:00
/**
* File: min_cost_climbing_stairs_dp.cpp
* Created Time: 2023-06-30
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* <20><>¥<EFBFBD><C2A5><EFBFBD><EFBFBD>С<EFBFBD><D0A1><EFBFBD>ۣ<EFBFBD><DBA3><EFBFBD>̬<EFBFBD>滮 */
int minCostClimbingStairsDP(vector<int> &cost) {
int n = cost.size() - 1;
if (n == 1 || n == 2)
return cost[n];
// <20><>ʼ<EFBFBD><CABC> dp <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڴ洢<DAB4><E6B4A2><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ľ<EFBFBD>
vector<int> dp(n + 1);
// <20><>ʼ״̬<D7B4><CCAC>Ԥ<EFBFBD><D4A4><EFBFBD><EFBFBD>С<EFBFBD><D0A1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ľ<EFBFBD>
dp[1] = cost[1];
dp[2] = cost[2];
// ״̬ת<CCAC>ƣ<EFBFBD><C6A3>ӽ<EFBFBD>С<EFBFBD><D0A1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ϴ<EFBFBD><CFB4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
for (int i = 3; i <= n; i++) {
dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i];
}
return dp[n];
}
/* <20><>¥<EFBFBD><C2A5><EFBFBD><EFBFBD>С<EFBFBD><D0A1><EFBFBD>ۣ<EFBFBD><DBA3>ռ<EFBFBD><D5BC>Ż<EFBFBD><C5BB><EFBFBD><EFBFBD>Ķ<EFBFBD>̬<EFBFBD>滮 */
int minCostClimbingStairsDPComp(vector<int> &cost) {
int n = cost.size() - 1;
if (n == 1 || n == 2)
return cost[n];
int a = cost[1], b = cost[2];
for (int i = 3; i <= n; i++) {
int tmp = b;
b = min(a, tmp) + cost[i];
a = tmp;
}
return b;
}
/* Driver Code */
int main() {
vector<int> cost = {0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1};
cout << "<EFBFBD><EFBFBD><EFBFBD><EFBFBD>¥<EFBFBD>ݵĴ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>б<EFBFBD>Ϊ ";
printVector(cost);
int res = minCostClimbingStairsDP(cost);
cout << "<EFBFBD><EFBFBD><EFBFBD><EFBFBD>¥<EFBFBD>ݵ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʹ<EFBFBD><EFBFBD><EFBFBD>Ϊ " << res << endl;
res = minCostClimbingStairsDPComp(cost);
cout << "<EFBFBD><EFBFBD><EFBFBD><EFBFBD>¥<EFBFBD>ݵ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʹ<EFBFBD><EFBFBD><EFBFBD>Ϊ " << res << endl;
return 0;
}