Longest Palindromic Subsequence

problem [https://leetcode.com/problems/longest-palindromic-subsequence/ 516. Longest Palindromic Subsequence].

Problem description
Given a string, find the longest palindromic subsequence 's length in.

A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.


 * Example 1
 * Input: s = "bbbab"
 * Output: 4
 * Explanation: One possible longest palindromic subsequence is "bbbb".


 * Example 2
 * Input: s = "cbbd"
 * Output: 2
 * Explanation: One possible longest palindromic subsequence is "bb".


 * Constraints
 * consists only of lowercase English letters.
 * consists only of lowercase English letters.

Problem analysis
We can use dynamic programming to solve the problem, by starting from looking at substrings of input with length 1, and then repeatedly consider longer substrings that contain shorter substrings, since a palindromic subsequence in a shorter substring will also exist in all longer substrings that contain this shorter substring. For example, if a shorter substring has a palindromic subsequence with length 5, then all longer substrings containing this shorter substring will have a palindromic subsequence with length of at least 5.
 * Example: "abcdeba" contains a subsequence of length 5 ("abcba"). Then, since "eabcdebad" contains "abcdeba", the former string also has a palindromic subsequence with at least length 5.

Now we want to find out the transition relationships.

Let  be the length of input. We can create a table  with   rows and   columns. Let  represent the length of longest palindromic subsequence in.
 * Base case 1: For all substrings of length 1, the longest palindromic subsequence has length 1 (the substrings themselves).
 * Base case 2: For all substrings of length 2:
 * If  then.
 * Otherwise.
 * Transition equations for substrings of length 3 or longer:
 * If, then we look at  , i.e. the longest palindromic subsequence in the substring excluding   and  , and then add 2 to get  . So.
 * Otherwise, putting in  and   will not create a longer palindromic subsequence than the longest palindromic subsequence in  . But the substrings   or   may contain a longest palindromic subsequence longer than that in  . So.

We can fill in the table starting from substrings of length 1, and proceed step by step until we reach the substring length of. Finally the result will be.

Working example

 * Input: "eabcdebad"
 * Output:  ("abcba")

Complexity analysis
Let  be the length of input string.


 * Space complexity
 * Since we created the  table with   rows and   columns, the space complexity is O( 2).


 * Time complexity
 * Since the amount to fill in each cell in the  table is constant, the total time complexity is also O( 2).