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

300. 最长递增子序列

记忆化搜索

class Solution:
    def lengthOfLIS(self, nums: List[int]):
        @cache
        def dfs(i):
            res = 0
            for j in range(i):
                if nums[j] < nums[i]:
                    res = max(res, dfs(j))
            return res + 1
        return max(dfs(i) for i in range(len(nums)))

674. 最长连续递增序列

枚举

class Solution {
public:
    int findLengthOfLCIS(vector& nums) {
        int ans = 0;
        if (nums.size() == 1) return 1;
        for (int i = 1; i < nums.size(); i++) {
            int len = 1;
            while (i < nums.size() && nums[i] > nums[i - 1]) {
                i++;
                len++;
            }
            ans = max(ans, len);
        }
        return ans;
    }
};

动规

class Solution {
public:
    int findLengthOfLCIS(vector& nums) {
        if (nums.size() == 0) return 0;
        int result = 1;
        vector dp(nums.size() ,1);
        for (int i = 1; i < nums.size(); i++) {
            if (nums[i] > nums[i - 1]) { // 连续记录
                dp[i] = dp[i - 1] + 1;
            }
            if (dp[i] > result) result = dp[i];
        }
        return result;
    }
};

718. 最长重复子数组

class Solution {
public:
    int findLength(vector& nums1, vector& nums2) {
        vector> dp (nums1.size() + 1, vector(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;
    }
};

你可能感兴趣的:(代码随想录,leetcode)