516. The longest palindrome subsequence (medium)

Ideas:

Starting from the length of 2, each length is traversed from left to right to get whether the length is satisfied ( overlap subproblem )

Add 1 to the length and compare whether it is satisfied. If not, then take the optimal solution of the previous length ( optimal solution problem )

 

Code:

class Solution {
    public int longestPalindromeSubseq(String s) {
		int n=s.length();
		
		//这里的dp表示长度,不表示数值
		int[][] dp=new int[n][n];
		
		//将dp的对角线元素置为1,意思是单个元素时,长度为1
		//因为是二维数组,不能用Arrays.fill()直接填满为1
		for(int i=0;i<n;i++){
			dp[i][i]=1;
		}
		
		//从2开始,逐个增加长度,不是累加,而是每次都是重新选值
                //len的条件设置为<=n
		for(int len=2;len<=n;len++){
			//从头开始遍历
			for(int i=0;i<n-len+1;i++){
                                //设置j为对应i这个头元素的尾元素
				int j=i+len-1;
				//若头尾的字符相同,符合条件,长度直接+len
				if(s.charAt(i)==s.charAt(j)){
					//dp[i+1][j-1]表示中间的最优解
					dp[i][j]=2+(len==2?0:dp[i+1][j-1]);
				}else{
					dp[i][j]=Math.max(dp[i+1][j],dp[i][j-1]);
				}
			}
		}
                //此时0~n-1是最优解,而不是还有1的可能
		return dp[0][n-1];
    }
}

 

break down:

1) Here dp is the second form: the current value depends on all the previously calculated values

Interval planning : generally use dp[i][j] to represent the best state or result from the i-th position to the j-th position

dp represents the length from the first number to the second number, then the subscript can be set to n, instead of n+1, there will be no subscript overflow problem

 

2) Set the diagonal to 1, which means that when a single element includes itself, the length of the palindrome subsequence is 1

for(int i=1;i<n;i++){
    dp[i][i]=1;
}

 

3) Only set double traversal (len, i)

It only needs to traverse the head i from the beginning to the end, and j only needs to move with the change of i each time, without j

for(int len=2;len<=n;len++)
	for(int i=0;i<n-len+1;i++)          
	    int j=i+len-1;

 

4) Core code:

When len==2, the head and tail meet the conditions, then the length is 2

When len==3, the head and tail meet the conditions, then the length is 2+the optimal solution dp[i+1][j-1]

                      If the head and tail do not meet the conditions, the length is the optimal solution between i and j, dp[i+1][j] or dp[i][j-1]

if(s.charAt(i)==s.charAt(j)){
    //dp[i+1][j-1]表示中间的最优解
    dp[i][j]=2+(len==2?0:dp[i+1][j-1]);
}else{
    dp[i][j]=Math.max(dp[i+1][j],dp[i][j-1]);
}

Guess you like

Origin blog.csdn.net/di_ko/article/details/115232281