求字符串的回文子序列个数
题目描述
求一个长度不超过15的字符串的回文子序列个数(子序列长度>=1)。
输入描述
输入一个长度不超过15的字符串,字符串均由小写字母表示
输出描述
输出其回文子序列个数
样例输入
abaa
样例输出
10
注释
本例中其所有回文子序列为:
a,b,a,a,aba,aba,aa,aa,aa,aaa
一个字符串的子序列是指在原字符串上去除某些字符但不破坏余下元素的相对位置(在前或在后)而形成的新字符串。
解题思路:
设字符串为str,长度为len,dp[i][j]表示第i到第j个字符间的最长子序列的长度(i<=j),则:状态初始条件: dp[j][j]=1 (j=0:n-1)
对于任意字符串,如果头尾字符不相等,则字符串的回文子序列个数=去掉头的字符串的回文子序列个数+去掉尾的字符串的回文子序列个数-去掉头尾的字符串的回文子序列个数; if(str[i]!=str[j]) dp[i][j]=dp[i+1][j] + dp[i][j-1] - dp[i+1][j-1];
如果头尾字符相等,则字符串的回文子序列个数=去掉头的字符串的回文子序列个数+去掉尾的字符串的回文子序列个数+ 1;
dp[i][j]=dp[i+1][j] + dp[i][j-1] +1 if(str[i]==str[j];
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int search(string str) { // num of palindrome subsequence
int len = str.length();
vector<vector<int>> dp(len, vector<int>(len)); //creat two-dimensional array for len*len
for (int j = 0; j < len; j++) { //from front to back
dp[j][j] = 1;
for (int i = j - 1; i >= 0; i--) { //from the back to the front
dp[i][j]=dp[i+1][j]+dp[i][j-1]-dp[i+1][j-1];
if(str[i]==str[j])
dp[i][j]+=1+dp[i+1][j-1];
}
}
return dp[0][len - 1];
}
int main()
{
string str;
cout << "Plz enter the num of palindrome subsequence: ";
cin >> str;
if (str.size() > 15) return false;
int num = search(str);
cout << "The num of palindrome subsequence is: " << num << endl;
return 0;
}