mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
@ -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:
|
||||
@ -230,3 +253,4 @@ function rob(nums: number[]): number {
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||
</a>
|
||||
|
||||
|
Reference in New Issue
Block a user