diff --git a/problems/0198.打家劫舍.md b/problems/0198.打家劫舍.md index 6e682ec3..7c8ba4db 100644 --- a/problems/0198.打家劫舍.md +++ b/problems/0198.打家劫舍.md @@ -141,7 +141,36 @@ class Solution { } } -// 空间优化 dp数组只存与计算相关的两次数据 +// 使用滚动数组思想,优化空间 +// 分析本题可以发现,所求结果仅依赖于前两种状态,此时可以使用滚动数组思想将空间复杂度降低为3个空间 +class Solution { + public int rob(int[] nums) { + + int len = nums.length; + + if (len == 0) return 0; + else if (len == 1) return nums[0]; + else if (len == 2) return Math.max(nums[0],nums[1]); + + + int[] result = new int[3]; //存放选择的结果 + result[0] = nums[0]; + result[1] = Math.max(nums[0],nums[1]); + + + for(int i=2;i nums[1] ? nums[0] : nums[1]; + dp[1] = Math.max(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]; + res = Math.max((dp[0] + nums[i]) , dp[1] ); dp[0] = dp[1]; dp[1] = res; } diff --git a/problems/0718.最长重复子数组.md b/problems/0718.最长重复子数组.md index 08be6732..31782d5d 100644 --- a/problems/0718.最长重复子数组.md +++ b/problems/0718.最长重复子数组.md @@ -198,7 +198,57 @@ public: 而且为了让 `if (dp[i][j] > result) result = dp[i][j];` 收集到全部结果,两层for训练一定从0开始遍历,这样需要加上 `&& i > 0 && j > 0`的判断。 -相对于版本一来说还是多写了不少代码。而且逻辑上也复杂了一些。 优势就是dp数组的定义,更直观一点。 +对于基础不牢的小白来说,在推导出转移方程后可能疑惑上述代码为什么要从`i=0,j=0`遍历而不是从`i=1,j=1`开始遍历,原因在于这里如果不是从`i=0,j=0`位置开始遍历,会漏掉如下样例结果: +```txt +nums1 = [70,39,25,40,7] +nums2 = [52,20,67,5,31] +``` + +当然,如果你愿意也可以使用如下代码,与上面那个c++是同一思路: +```java +class Solution { + public int findLength(int[] nums1, int[] nums2) { + int len1 = nums1.length; + int len2 = nums2.length; + int[][] result = new int[len1][len2]; + + int maxresult = Integer.MIN_VALUE; + + for(int i=0;i