【leetcode】516. Longest Palindromic Subsequence
题目如下:
解题思路:很经典的动态规划题目,但是用python会超时,只好用C++了。
代码如下:
class Solution { public: int longestPalindromeSubseq(string s) { int dp[1001][1001] = {0}; int res = 1; for (int i = s.length()-1;i >=0;i--){ for (int j = i+1;j<s.length();j++){ dp[i][i] = 1; if (s[i] == s[j]){ dp[i][j] = dp[i][j] > dp[i+1][j-1]+2 ? dp[i][j] :dp[i+1][j-1]+2; } else{ dp[i][j] = dp[i][j-1] > dp[i+1][j] ? dp[i][j-1] : dp[i+1][j]; } res = res > dp[i][j] ? res : dp[i][j]; } } return res; } };