代码随想录算法训练营第五十三天|动态规划part14|● 1143.最长公共子序列 ● 1035.不相交的线 ● 53. 最大子序和 动态规划

●  1143.最长公共子序列 Longest Common Subsequence - LeetCode

dp[i][j] 以[0, i- 1]和[0, j - 1]这两个最长公共子序列,比较元素是否相同

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

else dp[i][j] = max(dp[i][j - 1], dp[i - 1][j])

初始化:

dp[i][0] = 0

dp[0][j] = 0

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

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

return dp[nums1.length][nums2.length]

class Solution {
    public int longestCommonSubsequence(String text1, String text2) {
        int m = text1.length();
        int n = text2.length();
        int[][] dp = new int[m + 1][n + 1];
        dp[0][0] = 0;

        for (int i = 1; i <= m; i++) {
             char c1 = text1.charAt(i - 1);
            for (int j = 1; j <= n; j++) {
                char c2 = text2.charAt(j - 1);
                if (c1 == c2) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        return dp[m][n];
    }
}

●  1035.不相交的线   Uncrossed Lines - LeetCode

最长公共子序列

class Solution {
    public int maxUncrossedLines(int[] nums1, int[] nums2) {
        int m = nums1.length;
        int n = nums2.length;
        int[][] dp = new int[m + 1][n + 1];
        dp[0][0] = 0;

        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (nums1[i - 1] == nums2[j - 1]) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        return dp[m][n];
    }
}

●  53. 最大子序和  动态规划 Maximum Subarray - LeetCode

class Solution {
    public int maxSubArray(int[] nums) {
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        int res = nums[0];

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

        return res;
    }
}

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