Open carloscn opened 1 year ago
static int32_t min_cost_climbing(const int32_t *cost, size_t len, int32_t *spend)
{
int32_t ret = 0;
size_t i = 0;
int32_t *dp = NULL;
UTILS_CHECK_PTR(cost);
UTILS_CHECK_PTR(spend);
UTILS_CHECK_LEN(len);
dp = (int32_t *)calloc(sizeof(uint32_t), len + 1);
UTILS_CHECK_PTR(dp);
for (i = 2; i <= len; i ++) {
dp[i] = UTILS_MIN(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);
}
*spend = dp[len];
finish:
UTILS_SAFE_FREE(dp);
return ret;
}
fn min_cost_climbing(cost:&Vec<i32>) -> Result<i32, &'static str>
{
let mut dp:Vec<i32> = Vec::new();
let mut i:usize = 2;
if cost.len() < 1 {
return Err("the input cost error!");
}
dp.push(0);
dp.push(0);
while i <= cost.len() {
let pre_dp = dp[i - 2] + cost[i - 2];
let post_dp = dp[i - 1] + cost[i - 1];
dp.push(std::cmp::min(pre_dp, post_dp));
i += 1;
}
return Ok(dp[cost.len()]);
}
问题描述
给你一个整数数组 cost ,其中 cost[i] 是从楼梯第 i 个台阶向上爬需要支付的费用。一旦你支付此费用,即可选择向上爬一个或者两个台阶。
你可以选择从下标为 0 或下标为 1 的台阶开始爬楼梯。
请你计算并返回达到楼梯顶部的最低花费。
示例 1:
输入:cost = [10,15,20] 输出:15 解释:你将从下标为 1 的台阶开始。
输入:cost = [1,100,1,1,1,100,1,1,100,1] 输出:6 解释:你将从下标为 0 的台阶开始。
提示:
2 <= cost.length <= 1000 0 <= cost[i] <= 999
来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/min-cost-climbing-stairs