Longest Palindromic Subsequence
c != d
cddpd
ddpd cddp
c != p
d == d
count = 2
dp
d != p
p d
p == p
count = 1
d == d
count = 1
2 + 1 = 3
if(startIndex == endIndex)
return 1;
// case 1: beginning and the end are the same
if(st.charAt(startIndex) == st.charAt(endIndex))
return 2 + lpsLengthRecursive(st, startIndex+1, endIndex-1);
// case 2: skip one element either from the beginning or the end
int r1 = lpsLengthRecursive(startIndex+1, endIndex);
int r2 = lpsLengthRecursive(startIndex, endIndex-1);
return Math.max(r1, r2);
Run time: 2 ^ n
if(startIndex == endIndex)
return 1;
// case 1: beginning and the end are the same
if(st.charAt(startIndex) == st.charAt(endIndex))
return 2 + lpsLengthRecursive(st, startIndex+1, endIndex-1);
// case 2: skip one element either from the beginning or the end
int r1 = lpsLengthRecursive(startIndex+1, endIndex);
int r2 = lpsLengthRecursive(startIndex, endIndex-1);
return Math.max(r1, r2);