algorighm/dynamic-programming/subsequence/718最长重复子数组.js

38 lines
1.1 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
const findLength = function (nums1, nums2) {
};
/*
定义dp[i][j]表示nums1从i开始nums2从j开始的最长子数组的长度dp[i][j]可以由两种情况得来第一种当nums1[i] !== nums2[j],
那么从这个位置开始的子数组就不可能是公共子数组多以dp[i][j] = 0;第二种当nums1[i] === nums2[j] 那么dp[i][j] = 1 + dp[i+1][j+1]
得来。
*/
function f1(nums1, nums2) {
const m = nums1.length;
const n = nums2.length;
let result = 0;
// 定义dp表并且初始化
const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
// 按照dp[i][j]的定义我们需要从下到上从右到左填充dp数组
for (let i = m - 1; i >= 0; i--) {
for (let j = n - 1; j >= 0; j--) {
if (nums1[i] === nums2[j]) {
dp[i][j] = 1 + dp[i + 1][j + 1];
result = Math.max(result, dp[i][j]);
} else {
dp[i][j] = 0;
}
}
}
console.log(dp);
return result;
}
f1([0, 0, 0, 0, 1], [0, 0, 0, 0, 1]);