1143. Longest Common Subsequence

找两组数据的最大数值,可以自顶向下写个递归,把可能重复的部分记录下来,用一个二维数组来存储:

class Solution {
    private Integer[][] dp;
    private int m, n;
    public int longestCommonSubsequence(String text1, String text2) {
        m = text1.length(); 
        n = text2.length();
        dp = new Integer[m][n];
        return helper(text1, text2, 0, 0);
    }
    
    private int helper(String text1, String text2, int i, int j) {
        if (i == m || j == n)
            return 0;
        
        if (dp[i][j] != null)
            return dp[i][j];
            
        if (text1.charAt(i) == text2.charAt(j))
            return dp[i][j] = 1 + helper(text1, text2, i + 1, j + 1);
        else
            return dp[i][j] = Math.max(
                helper(text1, text2, i + 1, j),
                helper(text1, text2, i, j + 1)
            );
    }
}

上面的自顶向下算法可以演变成下面的自底向上的算法,而且抛弃递归:

class Solution {
    public int longestCommonSubsequence(String text1, String text2) {
        int m = text1.length(), n = text2.length();
        int[][] dp = new int[m+1][n+1];
        for(int i=0;i<m;i++){
            for ( int j=0;j<n;j++){
                if(text1.charAt(i)==text2.charAt(j)){
                    dp[i+1][j+1]=dp[i][j]+1;
                }else{
                    dp[i+1][j+1]=Math.max(dp[i][j+1], dp[i+1][j]);
                }
            }
        }
        return dp[m][n];
    }
}

 

上一篇:IDEA中Maven Helper插件的安装及使用


下一篇:7.环形的单向链表