简单的递归题

题目如下:

Problem Description
最近郁闷的汪欧涛遇到了一个难题,他的队友小成成给了他一道问题,对于一串随机的字符串(均由小写字母组成),去掉任意位置上任意数量的字符,可以得到的最长的回文串长度是多少,这可把汪欧涛给难住了,你作为他的好朋友,你能帮他解决这个问题吗?
ps:“回文串”是一个正读和反读都一样的字符串,例如“abcba”,“a”,“adeeda”是回文串,而“abcd”,‘adc’不是。 
Input
输入多组字符串,每组字符串皆由小写字母组成,每组字符串的长度不超过10。 
Output
对于每组字符串,输出一个整数在一行,代表其能组成的回文串的最大长度。 
Sample Input
abca

abdefacaed

aaaaaaaaaa
Sample Output
3
7
10

思路:  可以用一个类似于二进制的数组存储,a[i]=0则表示第i个位置不出现,1则出现(此处我还用了递归,其实10个for应该也是能过的,毕竟数据有点小)

AC代码:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char s[20];
bool vis[20];
int ans,len;
void find()
{
    int temp,cnt=0,r=1,l=len,fag=1;
    for (int i=1;i<=len;i++){
        if (vis[i])
            cnt++;
    }
    while (r<=l){
//        cout<<r<<"	"<<l<<endl;
        while (vis[r]==0&&r<=l){
            r++;
        }
        while (vis[l]==0&&r<=l){
            l--;
        }
        if (r<=l&&s[r]!=s[l]){
            fag=0;
            break;
        }
        else{
            r++;
            l--;
        }
    }
    if (fag)
        ans=ans>cnt?ans:cnt;
}
void check(int pos){
//    cout<<"1*"<<endl;
    if (pos>len+1)
        return ;
    if (pos==len+1){
        find();
        return ;
    }
    vis[pos]=true;
    check(pos+1);
    vis[pos]=false;
    check(pos+1);
    return ;
}
int main()
{
    while(cin>>s+1){
        memset(vis,true,sizeof(vis));
        len=strlen(s+1);
        check(1);
        cout<<ans<<endl;
    }
    return 0;
} 
原文地址:https://www.cnblogs.com/q1204675546/p/9960589.html