1. 程式人生 > >字符串的回文子序列個數

字符串的回文子序列個數

一個 space war AI sea strong 去除 earch ID

題目描述

求一個長度不超過15的字符串的回文子序列個數(子序列長度>=1)。


輸入描述

輸入一個長度不超過15的字符串,字符串均由小寫字母表示


輸出描述

輸出其回文子序列個數


樣例輸入

abaa


樣例輸出

10


註釋

本例中其所有回文子序列為:
a,b,a,a,aba,aba,aa,aa,aa,aaa
一個字符串的子序列是指在原字符串上去除某些字符但不破壞余下元素的相對位置(在前或在後)而形成的新字符串。

#include<iostream>
#include<string>

using
namespace std; string str,creat=""; int ans=-1; bool used[20]={false}; bool back_forward(string str) { for(int i=0;i<str.length()/2;i++) { if(str[i]!=str[str.length()-i-1]) return false; } return true; } void search(int len, int start) { if(len<=0) {
if (back_forward(creat)) {/*cout<<creat<<endl;*/ans++;} return; } for(int i=start;i<str.length();i++) { if (!used[i]) { used[i]=true; creat.append(str,i,1); search(len-1,i+1); used[i]=false; creat.erase(creat.length()
-1,1); } } } int main(){ cin>>str; for(int i=0;i<str.length();i++) search(i,0); if (back_forward(str)) {/*cout<<str<<endl;*/ans++;} cout<<ans<<endl; return 0; }

字符串的回文子序列個數