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 { +