力扣198打家劫舍补充(滚动数组)
补充力扣198打家劫舍动态规划-CSDN博客的滚动数组写法只有小改动原未使用滚动数组代码class Solution { public int rob(int[] nums) { int length nums.length; if(nums null || length 0){ return 0; } if(length 1){return nums[0];} int[] dp new int[length]; dp[0] nums[0]; dp[1] Math.max(nums[0],nums[1]); for (int i 2; i length; i){ dp[i] Math.max(dp[i - 2] nums[i] , dp[i-1]); } return dp[length - 1]; } }使用了数组存储结果。考虑到每间房屋的最高总金额只和该房屋的前两间房屋的最高总金额相关因此可以使用滚动数组在每个时刻只需要存储前两间房屋的最高总金额。即只用两个变量滚动保存前两状态代替dp数组看代码class Solution { public int rob(int[] nums) { if (nums null || nums.length 0) { return 0; } int length nums.length; if (length 1) { return nums[0]; } //区别从这里开始 int first nums[0], second Math.max(nums[0], nums[1]); for (int i 2; i length; i) { int temp second; second Math.max(first nums[i], second); first temp; } return second; } }[ first , second , nums[i] ]滑动数组大致长这样first到 i-2 位置能偷到的最大金额second到 i-2 位置能偷到的最大金额temp先存旧second值也可以说是nums[i-1]的值后面赋值给first为什么要赋值给first 很好理解数组向后滑动一位则first即为上一次second的值同理second是上一位nums[i]的值新的nums[i]其实是上一轮的num[i1]了仿照第一轮把temp赋值为现在数组的second接着重复就行了每一轮只看数字增加的值其实只有second只看数字不说谁取谁的值