516. Longest Palindromic Subsequence

Question

LeetCode Problem

Given a string s, return the length of the longest palindromic subsequence in s.

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:


Solutions

Use DP

int longestPalidromeSubseq(string s) {
	int m = static_cast<int>(s.size());
	if (m == 0) return 0;
	vector<vector<int>> dp(m, vector<int>(m, 0));
	
	for (int i = 0; i < m; ++i) {
		dp[i][i] = 1;
	}
	
	for (int i = (m - 1); i >= 0; i--) {
		for (int j = i + 1; j < m; ++j) {
			if (s[i] == s[j]) {
				dp[i][j] = dp[i+1][j-1] + 2;
			} else {
				dp[i][j] = max(dp[i][j-1], dp[i+1][j]);
			}
		}
	}
	
	return dp[0][m-1];
}