From ce73cef055f17879a9ef8f58f8cabffd48ed7edb Mon Sep 17 00:00:00 2001 From: jimowo <1252480844@qq.com> Date: Mon, 24 Apr 2023 16:16:16 +0800 Subject: [PATCH] =?UTF-8?q?=E7=AE=97=E6=B3=95=E7=A9=BA=E9=97=B4=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/0198.打家劫舍.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/0198.打家劫舍.md b/problems/0198.打家劫舍.md index c25f3b86..6e7f5ab6 100644 --- a/problems/0198.打家劫舍.md +++ b/problems/0198.打家劫舍.md @@ -136,6 +136,29 @@ class Solution { return dp[nums.length - 1]; } } + +// 空间优化 dp数组只存与计算相关的两次数据 +class Solution { + public int rob(int[] nums) { + if (nums.length == 1) { + return nums[0]; + } + // 初始化dp数组 + // 优化空间 dp数组只用2格空间 只记录与当前计算相关的前两个结果 + int[] dp = new int[2]; + dp[0] = nums[0]; + dp[1] = nums[0] > nums[1] ? nums[0] : nums[1]; + int res = 0; + // 遍历 + for (int i = 2; i < nums.length; i++) { + res = (dp[0] + nums[i]) > dp[1] ? (dp[0] + nums[i]) : dp[1]; + dp[0] = dp[1]; + dp[1] = res; + } + // 输出结果 + return dp[1]; + } +} ``` Python: @@ -220,3 +243,4 @@ function rob(nums: number[]): number { +