第九章 动态规划part13

60 阅读1分钟

300. Longest Increasing Subsequence

Given an integer array nums, return the length of the longest strictly increasing

subsequence.

题目解析:

  • 使用动态规划,dp[i]表示包含以i元素结尾的最长递增序列。

代码:

class Solution {
    public int lengthOfLIS(int[] nums) {
        int[] dp = new int[nums.length];
        int result = 0;
        for (int i = 0; i < nums.length; i++) {
            dp[i] = 1;
            for (int j = 0; j < i; j++) {
                if (nums[j] < nums[i]) {
                    dp[i] = Math.max(dp[i], dp[j] + 1);
                }
            }
            result = Math.max(result, dp[i]);
        }
        return result;
    }
}

674. Longest Continuous Increasing Subsequence

Given an unsorted array of integers nums, return the length of the longest continuous increasing subsequence (i.e. subarray) . The subsequence must be strictly increasing.

continuous increasing subsequence is defined by two indices l and r (l < r) such that it is [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] and for each l <= i < rnums[i] < nums[i + 1].

题目解析:

  • 找出所有连续递增子串,判断最长子串

代码:

class Solution {
    public int findLengthOfLCIS(int[] nums) {
        int result = 0;
        int left = 0, right = 0;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > nums[i-1]) {
                right = i;
            } else {
                result = Math.max(result, right - left + 1);
                left = i;
                right = i;
            }
        }
        return Math.max(result, right - left + 1);
    }
}

718. Maximum Length of Repeated Subarray

Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays.

题目解析:

  • dp[i][j] 代表以nums1中包含i结尾的子串 与 nums2中包含j的子串的最长重复值。

代码:

class Solution {
    public int findLength(int[] nums1, int[] nums2) {
        int[][] dp = new int[nums1.length+1][nums2.length+1];
        int result = 0;
        for (int i = 0; i < nums1.length; i++) {
            for (int j = 0; j < nums2.length; j++) {
                if (nums1[i] == nums2[j]) {
                    dp[i+1][j+1] = dp[i][j] + 1;
                    result = Math.max(result, dp[i+1][j+1]);
                }
            }
        }
        return result;
    }
}