mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-13 06:06:11 +08:00
Update 0746.使用最小花费爬楼梯.md
This commit is contained in:
@ -351,17 +351,29 @@ function minCostClimbingStairs(cost: number[]): number {
|
|||||||
### Rust
|
### Rust
|
||||||
|
|
||||||
```Rust
|
```Rust
|
||||||
use std::cmp::min;
|
|
||||||
impl Solution {
|
impl Solution {
|
||||||
pub fn min_cost_climbing_stairs(cost: Vec<i32>) -> i32 {
|
pub fn min_cost_climbing_stairs(cost: Vec<i32>) -> i32 {
|
||||||
let len = cost.len();
|
let mut dp = vec![0; cost.len() + 1];
|
||||||
let mut dp = vec![0; len];
|
for i in 2..=cost.len() {
|
||||||
dp[0] = cost[0];
|
dp[i] = (dp[i - 1] + cost[i - 1]).min(dp[i - 2] + cost[i - 2]);
|
||||||
dp[1] = cost[1];
|
|
||||||
for i in 2..len {
|
|
||||||
dp[i] = min(dp[i-1], dp[i-2]) + cost[i];
|
|
||||||
}
|
}
|
||||||
min(dp[len-1], dp[len-2])
|
dp[cost.len()]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
不使用 dp 数组
|
||||||
|
|
||||||
|
```rust
|
||||||
|
impl Solution {
|
||||||
|
pub fn min_cost_climbing_stairs(cost: Vec<i32>) -> i32 {
|
||||||
|
let (mut dp_before, mut dp_after) = (0, 0);
|
||||||
|
for i in 2..=cost.len() {
|
||||||
|
let dpi = (dp_before + cost[i - 2]).min(dp_after + cost[i - 1]);
|
||||||
|
dp_before = dp_after;
|
||||||
|
dp_after = dpi;
|
||||||
|
}
|
||||||
|
dp_after
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
Reference in New Issue
Block a user