leetcode-300-最长递增子序列
dp[i]表示i之前包括i的以nums[i]结尾的最长递增子序列的长度
dp[j]是(0,i-1)不包括i的以nums[i-1]结尾的最长递增子序列长度
int lengthOfLIS(int* nums, int numsSize) {if(numsSize <= 1)return numsSize;int dp[numsSize];for(int i = 0 ; i < numsSize ; i++){dp[i] = 1;}int res = 1;for(int i = 1 ; i < numsSize ; i++){for(int j = 0 ; j < i ; j++){if(nums[i] > nums[j])dp[i] = fmax(dp[i],dp[j]+1);}res = fmax(res,dp[i]);}return res;
}
leetcode-674-最长连续递增序列
不连续递增子序列的跟前0-i 个状态有关,连续递增的子序列只跟前一个状态有关
int findLengthOfLCIS(int* nums, int numsSize) {if(numsSize <= 1)return numsSize;int dp[numsSize];for(int i = 0 ; i < numsSize ; i++)dp[i] = 1;int res = 0;for(int i = 1 ; i < numsSize ; i++){if(nums[i] > nums[i-1])dp[i] = dp[i-1]+1;res = fmax(res,dp[i]);}return res;
}
leetcode-718-最长重复子数组
dp[i][j] :以下标i - 1为结尾的A,和以下标j - 1为结尾的B,最长重复子数组长度为dp[i][j]。
int findLength(int* nums1, int nums1Size, int* nums2, int nums2Size) {int dp[nums1Size+1][nums2Size+1];for(int i = 0 ; i <= nums1Size ; i++){memset(dp[i],0,sizeof(int)*(nums2Size+1));}int res = 0;for(int i = 1 ; i <= nums1Size ; i++){for(int j = 1 ; j <= nums2Size ; j++){if(nums1[i-1] == nums2[j-1]){dp[i][j] = dp[i-1][j-1]+1;}res = fmax(res,dp[i][j]);}}return res;
}
leetcode-1143-最长公共子序列
区别于 349.两个数组交集
int longestCommonSubsequence(char* text1, char* text2) {int len1 = strlen(text1);int len2 = strlen(text2);int dp[len1+1][len2+1];for(int i = 0 ; i <= len1 ; i++){memset(dp[i],0,sizeof(int)*(len2+1));}for(int i = 1 ; i <= len1 ; i++){for(int j = 1 ; j <= len2 ; j++){if(text1[i-1] == text2[j-1]){dp[i][j] = dp[i-1][j-1]+1;}else{dp[i][j] = fmax(dp[i-1][j],dp[i][j-1]);}}}return dp[len1][len2];
}
leetcode-1035-不相交的线
本质是求最长公共子序列
int maxUncrossedLines(int* nums1, int nums1Size, int* nums2, int nums2Size) {int dp[nums1Size+1][nums2Size+1];for(int i = 0 ; i <= nums1Size ; i++){memset(dp[i],0,sizeof(int)*(nums2Size+1));}for(int i = 1 ; i <= nums1Size ; i++){for(int j = 1 ; j <= nums2Size ; j++){if(nums1[i-1] == nums2[j-1]){dp[i][j] = dp[i-1][j-1]+1;}else{dp[i][j] = fmax(dp[i-1][j],dp[i][j-1]);}}}return dp[nums1Size][nums2Size];
}