300最长递增子序列
cpp
class Solution {
public:
int lengthOfLIS(vector<int>& nums)
{
int piles = 0; // 牌堆数初始化为 0
vector<int> top(nums.size()); // 牌堆数组 top
for (int i = 0; i < nums.size(); i++)
{
int poker = nums[i];
int left = 0, right = piles;
while (left < right)
{
int mid = (left + right) / 2;
if (top[mid] < poker)
{
left = mid + 1;
} else {
right = mid;
}
}
if (left == piles) piles++;
top[left] = poker;
}
// 牌堆数就是 LIS 长度
return piles;
}
};
674最长连续递增子序列
cpp
class Solution {
public:
int findLengthOfLCIS(vector<int>& nums)
{
int result=0;
if(nums.size()<=1) return nums.size();
vector<int>dp(nums.size(),1);
for(int i=1;i<nums.size();i++)
{
if(nums[i]>nums[i-1]) dp[i]=max(dp[i],dp[i-1]+1);
result=dp[i]>result?dp[i]:result;
}
return result;
}
};
718最长重复子数组
cpp
class Solution {
public:
int findLength(vector<int>& nums1, vector<int>& nums2)
{
vector<vector<int>> dp (nums1.size() + 1, vector<int>(nums2.size() + 1, 0));
int result = 0;
for(int i=1;i<=nums1.size();i++)
{
for(int j=1;j<=nums2.size();j++)
{
if(nums1[i-1]==nums2[j-1])
{
dp[i][j]=dp[i-1][j-1]+1;
if (dp[i][j] > result) result = dp[i][j];
}
}
}
return result;
}
};