leetcode: 516.最长回文子序列(动态规划)

链接:https://leetcode-cn.com/problems/longest-palindromic-subsequence/
创建一个二维数组 d p dp dp d p [ i ] [ j ] dp[i][j] dp[i][j]表示字符串下标从 i i i j j j的子串的最长回文子序列。
s [ i ] = = s [ j ] s[i]==s[j] s[i]==s[j],则 d p [ i ] [ j ] = d p [ i + 1 ] [ j − 1 ] + 2 dp[i][j]=dp[i+1][j-1]+2 dp[i][j]=dp[i+1][j1]+2(为什么?)
s [ i ] ! = s [ j ] s[i]!=s[j] s[i]!=s[j], 则 d p [ i ] [ j ] = M A X ( d p [ i + 1 ] [ j ] , d p [ i ] [ j − 1 ] ) dp[i][j]=MAX(dp[i+1][j],dp[i][j-1]) dp[i][j]=MAX(dp[i+1][j],dp[i][j1])
java代码:

class Solution {
    public int longestPalindromeSubseq(String s) {
        int dp[][] = new int[s.length()][s.length()];
        for(int i = s.length()-1;i>=0;i--)
        {
            for(int j = i;j<s.length();j++)
            {
                if(i==j)
                    dp[i][j] = 1;
                else 
                {
                    if(s.charAt(i)==s.charAt(j))
                        dp[i][j] = dp[i+1][j-1]+2;
                    else 
                        dp[i][j] = Math.max(dp[i+1][j],dp[i][j-1]);
                }
            }
        }
        return dp[0][s.length()-1];
    }
}

由于每一层的值仅与下一层有关,可做空间优化,注意需要一个变量存储原来二维数组“左下方”的值。
java代码:

class Solution {
    public int longestPalindromeSubseq(String s) {
        int dp[] = new int[s.length()+1];
        int temp =0;
        int last =0 ;
        for(int i = s.length();i>0;i--)
        {
            last= dp[i-1];
            for(int j = i;j<=s.length();j++)
            {
                temp = dp[j];
                if(i==j)
                    dp[j] = 1;
                else 
                {
                    if(s.charAt(i-1)==s.charAt(j-1))
                        dp[j] = last+2;
                    else 
                        dp[j] = Math.max(dp[j],dp[j-1]);
                }
                last = temp;
            }
        }
        return dp[s.length()];
    }
}

你可能感兴趣的:(leetcode,动态规划,leetcode,算法,java)