Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b660360

Browse files
Update 0718.最长重复子数组.md
1 parent 3b1a5f6 commit b660360

File tree

1 file changed

+51
-1
lines changed

1 file changed

+51
-1
lines changed

‎problems/0718.最长重复子数组.md‎

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,57 @@ public:
198198

199199
而且为了让 `if (dp[i][j] > result) result = dp[i][j];` 收集到全部结果,两层for训练一定从0开始遍历,这样需要加上 `&& i > 0 && j > 0`的判断。
200200

201-
相对于版本一来说还是多写了不少代码。而且逻辑上也复杂了一些。 优势就是dp数组的定义,更直观一点。
201+
对于基础不牢的小白来说,在推导出转移方程后可能疑惑上述代码为什么要从`i=0,j=0`遍历而不是从`i=1,j=1`开始遍历,原因在于这里如果不是从`i=0,j=0`位置开始遍历,会漏掉如下样例结果:
202+
```txt
203+
nums1 = [70,39,25,40,7]
204+
nums2 = [52,20,67,5,31]
205+
```
206+
207+
当然,如果你愿意也可以使用如下代码,与上面那个c++是同一思路:
208+
```java
209+
class Solution {
210+
public int findLength(int[] nums1, int[] nums2) {
211+
int len1 = nums1.length;
212+
int len2 = nums2.length;
213+
int[][] result = new int[len1][len2];
214+
215+
int maxresult = Integer.MIN_VALUE;
216+
217+
for(int i=0;i<len1;i++){
218+
if(nums1[i] == nums2[0])
219+
result[i][0] = 1;
220+
if(maxresult<result[i][0])
221+
maxresult = result[i][0];
222+
}
223+
224+
for(int j=0;j<len2;j++){
225+
if(nums1[0] == nums2[j])
226+
result[0][j] = 1;
227+
if(maxresult<result[0][j])
228+
maxresult = result[0][j];
229+
}
230+
231+
for(int i=1;i<len1;i++){
232+
for(int j=1;j<len2;j++){
233+
234+
if(nums1[i]==nums2[j])
235+
result[i][j] = result[i-1][j-1]+1;
236+
237+
if(maxresult<result[i][j])
238+
maxresult = result[i][j];
239+
240+
}
241+
242+
}
243+
244+
return maxresult;
245+
}
246+
}
247+
```
248+
249+
对于小白来说一定要明确dp数组中初始化的数据是什么
250+
251+
整体而言相对于版本一来说还是多写了不少代码。而且逻辑上也复杂了一些。 优势就是dp数组的定义,更直观一点。
202252

203253
## 其他语言版本
204254

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /