LeetCode516. 最长回文子序列 (动态规划)

经典的字符串动态规划,定义两个首尾指针i和j

状态初始条件:dp[ i ][ i ] = 1 ( i = 0 到 n - 1)
状态转移方程: if( s[ i ] == s[ j ] ):dp[ i ][ j ] = dp[ i + 1 ][ j - 1 ] + 2
                     : if ( s[ i ] != s [ j ] ):dp[ i ][ j ] = max( dp[ i + 1 ][ j ] , dp[ i ][ j - 1 ] )

https://leetcode-cn.com/problems/longest-palindromic-subsequence/

#include 
#include 
#include 
using namespace std;
class Solution {
public:
	int longestPalindromeSubseq(string s) {
		int i, j;
		int result = 1;
		vector<vector<int>> dp(s.size(), vector<int>(s.size(),0));
		for(j = 0; j < s.size(); ++j)
		{
			dp[j][j] = 1;
			for(i = j - 1; i >= 0; --i)
			{
				if(s[i] == s[j])
					dp[i][j] = dp[i + 1][j - 1] + 2;
				else
					dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]);
				result = max(result, dp[i][j]);
			}
		}
		return result;
	}
};

你可能感兴趣的:(LeetCode,动态规划,字符串,动态规划,回文)