From 6e92cd2417dea438d7671140fd73298a4b598c93 Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Sat, 18 Jun 2022 20:12:19 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200746.=E4=BD=BF=E7=94=A8?= =?UTF-8?q?=E6=9C=80=E5=B0=8F=E8=8A=B1=E8=B4=B9=E7=88=AC=E6=A5=BC=E6=A2=AF?= =?UTF-8?q?.md=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0746.使用最小花费爬楼梯.md | 30 ++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0746.使用最小花费爬楼梯.md b/problems/0746.使用最小花费爬楼梯.md index 5931fc8a..abaeb980 100644 --- a/problems/0746.使用最小花费爬楼梯.md +++ b/problems/0746.使用最小花费爬楼梯.md @@ -305,5 +305,35 @@ int minCostClimbingStairs(int* cost, int costSize){ return dp[i-1] < dp[i-2] ? dp[i-1] : dp[i-2]; } ``` + +### Scala + +```scala +object Solution { + def minCostClimbingStairs(cost: Array[Int]): Int = { + var dp = new Array[Int](cost.length) + dp(0) = cost(0) + dp(1) = cost(1) + for (i <- 2 until cost.length) { + dp(i) = math.min(dp(i - 1), dp(i - 2)) + cost(i) + } + math.min(dp(cost.length - 1), dp(cost.length - 2)) + } +} +``` + +第二种思路: dp[i] 表示爬到第i-1层所需的最小花费,状态转移方程为: dp[i] = min(dp[i-1]+cost[i-1],dp[i-2]+cost[i-2]) +```scala +object Solution { + def minCostClimbingStairs(cost: Array[Int]): Int = { + var dp = new Array[Int](cost.length + 1) + for (i <- 2 until cost.length + 1) { + dp(i) = math.min(dp(i - 1) + cost(i - 1), dp(i - 2) + cost(i - 2)) + } + dp(cost.length) + } +} +``` + -----------------------