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

300.最长递增子序列 Longest Increasing Subsequence - LeetCode

dp[i]以nums[i]结尾的最长子序列的长度

dp[i] = (dp[i], dp[j] + 1), j是遍历i以内的情况都和nums[i]比较

dp[i] = 1;

遍历顺序:从小到大

for(int i = 1; i < nums.length; i++)

        for (int j = 0; j <= i)//遍历0-i的所有元素

                if(nums[i] > nums[j]) 递推公式才成立

                        dp[i] = Math.max(dp[i], dp[j] + 1);

res = 0;

for (int i = 0; i < nums.length; i++)

        res = max(res, dp[i])

class Solution {
    public int lengthOfLIS(int[] nums) {
        int n = nums.length;
        int[] dp = new int[n];
       // dp[0] = 1;
        Arrays.fill(dp, 1);

        for (int i = 1; i < n; i++){
            for (int j = 0; j < i; j++) {
                if (nums[i] > nums[j]) {
                    dp[i] = Math.max(dp[i], dp[j] + 1);
                }
            }
        }
        int res = 0;
        for (int i = 0; i < dp.length; i++) {
            res = Math.max(res, dp[i]);
        }
        return res;
    }
}

●  674. 最长连续递增序列 Longest Continuous Increasing Subsequence - LeetCode

贪心 time: O(n), Space:O(1)

class Solution {
    public int findLengthOfLCIS(int[] nums) {
        int count = 1;
        int res = 1;

        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > nums[i - 1]) {
                count++;
            } else {
                count = 1;
            }
            if (count > res) res = count;
        }
        return res;
    }
}

dp,重点在连续两个字

class Solution {
    public int findLengthOfLCIS(int[] nums) {
        int[] dp = new int[nums.length];
        Arrays.fill(dp, 1);
        int res = 1;

        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > nums[i - 1]) {
                dp[i] = dp[i - 1] + 1;
            }
            if (dp[i] > res) res = dp[i];           
        }

        return res;
    }
}

●  718. 最长重复子数组 Maximum Length of Repeated Subarray - LeetCode

dp[i][j] 以i-1为结尾的nums1和以j-1为结尾的nums2的最长重复子数组长度

if(nums1[i - 1] == nums2[i - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;

for (int i = 1; i <= nums1.length; i++)

        for (int j = 1; j <= nums2.length; j++)

   

class Solution {
    public int findLength(int[] nums1, int[] nums2) {
        int len1 = nums1.length;
        int len2 = nums2.length;
        int[][] dp = new int[len1 + 1][len2 + 1];

        dp[0][0] = 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;
                }
                res = Math.max(res, dp[i][j]);
            }
        }
        return res;
    }
}

             

你可能感兴趣的:(代码随想录算法训练营,动态规划,算法)