|
|
|
@ -0,0 +1,53 @@
|
|
|
|
|
/**
|
|
|
|
|
* File: min_cost_climbing_stairs_dp.cs
|
|
|
|
|
* Created Time: 2023-06-30
|
|
|
|
|
* Author: hpstory (hpstory1024@163.com)
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
namespace hello_algo.chapter_dynamic_programming;
|
|
|
|
|
|
|
|
|
|
public class min_cost_climbing_stairs_dp {
|
|
|
|
|
/* 爬楼梯最小代价:动态规划 */
|
|
|
|
|
public int minCostClimbingStairsDP(int[] cost) {
|
|
|
|
|
int n = cost.Length - 1;
|
|
|
|
|
if (n == 1 || n == 2)
|
|
|
|
|
return cost[n];
|
|
|
|
|
// 初始化 dp 列表,用于存储子问题的解
|
|
|
|
|
int[] dp = new int[n + 1];
|
|
|
|
|
// 初始状态:预设最小子问题的解
|
|
|
|
|
dp[1] = cost[1];
|
|
|
|
|
dp[2] = cost[2];
|
|
|
|
|
// 状态转移:从较小子问题逐步求解较大子问题
|
|
|
|
|
for (int i = 3; i <= n; i++) {
|
|
|
|
|
dp[i] = Math.Min(dp[i - 1], dp[i - 2]) + cost[i];
|
|
|
|
|
}
|
|
|
|
|
return dp[n];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/* 爬楼梯最小代价:状态压缩后的动态规划 */
|
|
|
|
|
public int minCostClimbingStairsDPComp(int[] cost) {
|
|
|
|
|
int n = cost.Length - 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 = Math.Min(a, tmp) + cost[i];
|
|
|
|
|
a = tmp;
|
|
|
|
|
}
|
|
|
|
|
return b;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
[Test]
|
|
|
|
|
public void Test() {
|
|
|
|
|
int[] cost = { 0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1 };
|
|
|
|
|
Console.WriteLine("输入楼梯的代价列表为");
|
|
|
|
|
PrintUtil.PrintList(cost);
|
|
|
|
|
|
|
|
|
|
int res = minCostClimbingStairsDP(cost);
|
|
|
|
|
Console.WriteLine($"爬完楼梯的最低代价为 {res}");
|
|
|
|
|
|
|
|
|
|
res = minCostClimbingStairsDPComp(cost);
|
|
|
|
|
Console.WriteLine($"爬完楼梯的最低代价为 {res}");
|
|
|
|
|
}
|
|
|
|
|
}
|