Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6e92cd2

Browse files
committed
添加 0746.使用最小花费爬楼梯.md Scala版本
1 parent 5985aae commit 6e92cd2

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

‎problems/0746.使用最小花费爬楼梯.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,5 +305,35 @@ int minCostClimbingStairs(int* cost, int costSize){
305305
return dp[i-1] < dp[i-2] ? dp[i-1] : dp[i-2];
306306
}
307307
```
308+
309+
### Scala
310+
311+
```scala
312+
object Solution {
313+
def minCostClimbingStairs(cost: Array[Int]): Int = {
314+
var dp = new Array[Int](cost.length)
315+
dp(0) = cost(0)
316+
dp(1) = cost(1)
317+
for (i <- 2 until cost.length) {
318+
dp(i) = math.min(dp(i - 1), dp(i - 2)) + cost(i)
319+
}
320+
math.min(dp(cost.length - 1), dp(cost.length - 2))
321+
}
322+
}
323+
```
324+
325+
第二种思路: dp[i] 表示爬到第i-1层所需的最小花费,状态转移方程为: dp[i] = min(dp[i-1]+cost[i-1],dp[i-2]+cost[i-2])
326+
```scala
327+
object Solution {
328+
def minCostClimbingStairs(cost: Array[Int]): Int = {
329+
var dp = new Array[Int](cost.length + 1)
330+
for (i <- 2 until cost.length + 1) {
331+
dp(i) = math.min(dp(i - 1) + cost(i - 1), dp(i - 2) + cost(i - 2))
332+
}
333+
dp(cost.length)
334+
}
335+
}
336+
```
337+
308338
-----------------------
309339
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /