300.最长递增子序列
https://leetcode.cn/problems/longest-increasing-subsequence/
dp[i]表示i之前包括i的以nums[i]结尾的最长递增子序列的长度
位置i的最长升序子序列等于j从0到i-1各个位置的最长升序子序列 + 1 的最大值。所以:if (nums[i] > nums[j]) dp[i] = max(dp[i], dp[j] + 1);
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int len = nums.size();
if(len == 1) return 1;
vector<int> dp(len, 1);
int res = 0;
for(int i = 1; i < len; i++){
for(int j = 0; j < i; j++){
if(nums[i] > nums[j]) dp[i] = max(dp[i], dp[j] + 1);
}
if(dp[i] > res) res = dp[i];
}
return res;
}
};
674. 最长连续递增序列
https://leetcode.cn/problems/longest-continuous-increasing-subsequence/
dp[i]:以下标i为结尾的连续递增的子序列长度为dp[i]。
如果 nums[i] > nums[i - 1],那么以 i 为结尾的连续递增的子序列长度 一定等于 以i - 1为结尾的连续递增的子序列长度 + 1 。即:dp[i] = dp[i - 1] + 1;
class Solution {
public:
int findLengthOfLCIS(vector<int>& nums) {
int len = nums.size();
if(len == 1) return 1;
vector<int> dp(len, 1);
int res = 1;
for(int i = 1; i < len; i++){
if(nums[i] > nums[i - 1]) dp[i] = dp[i - 1] + 1;
if(dp[i] > res) res = dp[i];
}
return res;
}
};
718. 最长重复子数组
dp[i][j] :以下标i - 1为结尾的A,和以下标j - 1为结尾的B,最长重复子数组长度为dp[i][j]。 (特别注意: “以下标i - 1为结尾的A” 标明一定是 以A[i-1]为结尾的字符串 )
根据dp[i][j]的定义,dp[i][0] 和dp[0][j]其实都是没有意义的!但dp[i][0] 和dp[0][j]要初始值,因为 为了方便递归公式dp[i][j] = dp[i - 1][j - 1] + 1;所以dp[i][0] 和dp[0][j]初始化为0。
class Solution {
public:
int findLength(vector<int>& nums1, vector<int>& nums2) {
int len1 = nums1.size();
int len2 = nums2.size();
vector<vector<int>> dp(len1 + 1, vector<int>(len2 + 1, 0));
int res = 0;
for(int i = 1; i <= len1; i++){
for(int j = 1; j <= len2; j++){
if(nums1[i - 1] == nums2[j - 1]){
dp[i][j] = dp[i - 1][j - 1] + 1;
}
if(dp[i][j] > res) res = dp[i][j];
}
}
return res;
}
};