Solution: Longest Palindromic Subsequence
This review provides a detailed analysis of the different ways to solve the longest palindromic subsequence problem.
Solution 1: brute force
Explanation
By now, you must have noticed a pattern in the way we approach dynamic programming problems.
In this brute force solution,
- If the element at the beginning and the end are the same, we increase our count by two and make a recursive call for the remaining sequence (line 17 and 18)
- Otherwise, we skip the element either from the beginning or the end to make two recursive calls for the remaining subsequence. After that, we return the greater result (line 21 and 22)
Time complexity
The time complexity of the above algorithm is exponential , where n is the length of the input sequence. The space complexity is , which is the maximum number of times that the function is called, so, this is the space used to store the recursion stack.
Solution 2: memoization
Explanation
As done in memoization, we use an array, lookup_table, to store the values of the previously solved subproblems.
The two varying values in ...