The number of palindromic subsequences of the string

Topic description

Find the number of palindromic subsequences of a string whose length does not exceed 15 (subsequence length >= 1).


enter description

Enter a string with a length of no more than 15, all strings are represented by lowercase letters


output description

output the number of its palindrome subsequences


sample input

 

abaa


Sample output

10


Notes

In this example, all palindromic subsequences are:
a,b,a,a,aba,aba,aa,aa,aa,aaa
A subsequence of a string means removing certain characters from the original string without destroying the remaining elements A new string formed from the relative position (before or after) of .

#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;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325770116&siteId=291194637