From 571ddaa69d9ea4bd80dcad2b70ffc25ce84f78ae Mon Sep 17 00:00:00 2001 From: yangzhaoMP Date: Wed, 6 Mar 2024 11:41:56 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=A8=E6=80=81=E8=A7=84=E5=88=92=20?= =?UTF-8?q?=E7=88=AC=E6=A5=BC=E6=A2=AF=E6=9C=80=E5=B0=8F=E8=B4=B9=E7=8E=87?= =?UTF-8?q?=20java=20=E7=8A=B6=E6=80=81=E5=8E=8B=E7=BC=A9=E4=BC=98?= =?UTF-8?q?=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0746.使用最小花费爬楼梯.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/problems/0746.使用最小花费爬楼梯.md b/problems/0746.使用最小花费爬楼梯.md index d13ff19f..6320ed89 100644 --- a/problems/0746.使用最小花费爬楼梯.md +++ b/problems/0746.使用最小花费爬楼梯.md @@ -244,6 +244,24 @@ class Solution { } ``` +```Java +// 状态压缩,使用三个变量来代替数组 +class Solution { + public int minCostClimbingStairs(int[] cost) { + // 以下三个变量分别表示前两个台阶的最少费用、前一个的、当前的。 + int beforeTwoCost = 0, beforeOneCost = 0, currentCost = 0; + // 前两个台阶不需要费用就能上到,因此从下标2开始;因为最后一个台阶需要跨越,所以需要遍历到cost.length + for (int i = 2; i <= cost.length; i ++) { + // 此处遍历的是cost[i - 1],不会越界 + currentCost = Math.min(beforeOneCost + cost[i - 1], beforeTwoCost + cost[i - 2]); + beforeTwoCost = beforeOneCost; + beforeOneCost = currentCost; + } + return currentCost; + } +} +``` + ### Python 动态规划(版本一)