300.最长递增子序列
视频讲解:动态规划之子序列问题,元素不连续!| LeetCode:300.最长递增子序列_哔哩哔哩_bilibili
dp数组代表:以nums[i]为末尾的最长递增子序列的长度
dp[i] = Math.max(dp[i],dp[j] + 1); 因为可以不连续,j要从前往后都遍历一遍
初始化:全部为1
class Solution {
public int lengthOfLIS(int[] nums) {
int[] dp = new int[nums.length];
int result = 1;
Arrays.fill(dp,1);
for(int i = 1;i < nums.length;i++){
for(int j = 0;j < i;j++){
if(nums[i] > nums[j]){
dp[i] = Math.max(dp[i],dp[j] + 1);
}
}
result = Math.max(result,dp[i]);
}
return result;
}
}
674. 最长连续递增序列
视频讲解:动态规划之子序列问题,重点在于连续!| LeetCode:674.最长连续递增序列_哔哩哔哩_bilibili
连续,只需要考虑前面一个元素
class Solution {
public int findLengthOfLCIS(int[] nums) {
int len = nums.length;
int[] dp = new int[len];
Arrays.fill(dp,1);
int res = 1;
for(int i = 1;i < len;i++){
if(nums[i] > nums[i - 1]){
dp[i] = dp[i - 1] + 1;
//dp[i]初始值是1,dp[i - 1] + 1一定大,不用max
}
res = Math.max(res,dp[i]);
}
return res;
}
}
718. 最长重复子数组
视频讲解:动态规划之子序列问题,想清楚DP数组的定义 | LeetCode:718.最长重复子数组_哔哩哔哩_bilibili
nums[i] == nums[j] 时 ,左上角的数加一想到了,没有想到要初始化列
class Solution {
public int findLength(int[] nums1, int[] nums2) {
int[][] dp = new int[nums1.length][nums2.length];
int res = 0;
//初始化行
for(int i = 0;i < nums2.length;i++){
if(nums1[0] == nums2[i]){
dp[0][i] = 1;
res = 1;
}
}
//初始化列
for(int i = 1;i < nums1.length;i++){
if(nums2[0] == nums1[i]){
dp[i][0] = 1;
res = 1;
}
}
for(int i = 1;i < nums1.length;i++){
for(int j = 1;j < nums2.length;j++){
if(nums1[i] == nums2[j]){
//因为i j都要减一,所以行和列都要初始化
dp[i][j] = dp[i - 1][j - 1] + 1;
res = Math.max(res,dp[i][j]);
}
}
}
return res;
}
}
随想录的,不用初始化行和列,初始化直接全部赋零
class Solution {
public int findLength(int[] nums1, int[] nums2) {
int result = 0;
int[][] dp = new int[nums1.length + 1][nums2.length + 1];
for (int i = 1; i < nums1.length + 1; i++) {
for (int j = 1; j < nums2.length + 1; j++) {
if (nums1[i - 1] == nums2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
result = Math.max(result, dp[i][j]);
}
}
}
return result;
}
}
988

被折叠的 条评论
为什么被折叠?



