Problem:
Analysis:
DP 问题的核心就是转化为数学归纳法;
如果可以画出图就更好了
time O(n^2)
space O(n^2)
Code:
public int longestPalindromeSubseq(String s) {
if (s == null || s.length() == 0) return 0;
if(s.length() == 1 ) return 1;
int n = s.length();
int[][] M = new int[n][n];
// base case
for (int i=0; i<n; i++) {
M[i][i] = 1;
}
// inductive
for (int i=n-2; i>=0; i--) {
for (int j =i+1; j<n; j++) {
if (s.charAt(i) == s.charAt(j)) M[i][j] = 2 + M[i+1][j-1];
else M[i][j] = Math.max(M[i+1][j], M[i][j-1]);
}
}
return M[0][n-1];
}