代码随想录算法训练营第五十四天|300.最长递增子序列 ● 674. 最长连续递增序列 ● 718. 最长重复子数组

300. 最长递增子序列

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 result = 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);
            }
        }
        if (result < dp[i]) result = dp[i];
    } 
    return result;
}

674. 最长连续递增序列

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 result = 1;
    for (int i = 1; i < numsSize; i++)
    {
        if (nums[i] > nums[i-1]) {
            dp[i] = dp[i-1] + 1;
        }
        if (result < dp[i]) result = dp[i];
    }
    return result;
}

718. 最长重复子数组

dp[i][j] :以下标i - 1为结尾的A,和以下标j - 1为结尾的B,最长重复子数组长度为dp[i][j]。 (特别注意: “以下标i - 1为结尾的A” 标明一定是 以A[i-1]为结尾的字符串 )

int findLength(int* nums1, int nums1Size, int* nums2, int nums2Size){
    int dp[nums1Size+1][nums2Size+1];
    for (int i = 0; i <= nums1Size; i++)
    {
        for (int j = 0; j <= nums2Size; j++)
        {
            dp[i][j] = 0;
        }
    }
    int ans = 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;
            }
            if (ans < dp[i][j]) ans = dp[i][j];
        }
    }
    return ans;
}

你可能感兴趣的:(代码随想录算法,算法,数据结构,leetcode,c语言)