Longest Palindromic Subsequence

来源:互联网 发布:淘宝小号 周点数查询 编辑:程序博客网 时间:2024/06/06 20:52

        本次題目是有關於動態規劃的練習,Longest Palindromic Subsequence,目的是找出在給定的字串中最長的回蚊子字串的長度。

Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000.

Example 1:
Input:

"bbbab"

Output:

4

One possible longest palindromic subsequence is "bbbb".

Example 2:
Input:

"cbbd"

Output:

2

One possible longest palindromic subsequence is "bb".           

首先先確定子問題:

    基本情況
if i == j, 則longest[i][j] = 1, 
if i+1 == j, 則longest[i][j] = 2 if s[i] == s[j]
longest[i][j] = 1 否則

  1. s[i] == s[j]
    table[i][j] = max(table[i+1][j], table[i][j-1], table[i+1][j-1] + 2)
  2. s[i] != s[j]
    table[i][j] = max(table[i+1][j], dp[i][j-1], table[i+1][j-1])

再列出子問題之後就方便我們編程,透過創建二為數組table[i][j]記錄在s中I~J的最大長度,顯然最後要返回的值是table[0][size - 1]的答案,

int longestPalindromeSubseq(string s)
{
 if(s.empty())
  return 0;
 if(s.length() == 1)
  return 1;
 
 int size = s.length();
 vector<vector<int> > table(size, vector<int>(size, 0)); //初始化二為數組
 for(int i = 0; i < size; i++) table[i][i] = 1; //根據i == j, 則longest[i][j] = 1的情況,將 i==j的地方設為1


 for(int j = 1; j < size; j++)
 {
  for(int i = j - 1; i >= 0; i--)
  {
   if(s[i] == s[j])    //為動態規劃的判斷語句
    table[i][j] = max(max(table[i + 1][j], table[i][j - 1]), 2 + table[i + 1][j - 1]);
   else
    table[i][j] = max(table[i + 1][j], table[i][j - 1]);
  }
 }
 return table[0][size - 1];
}