【算法题】暗黑的字符串

来源:互联网 发布:专科 知乎 编辑:程序博客网 时间:2024/05/10 01:20

一个只包含’A’、’B’和’C’的字符串,如果存在某一段长度为3的连续子串中恰好’A’、’B’和’C’各有一个,那么这个字符串就是纯净的,否则这个字符串就是暗黑的。例如:
BAACAACCBAAA 连续子串”CBA”中包含了’A’,’B’,’C’各一个,所以是纯净的字符串
AABBCCAABB 不存在一个长度为3的连续子串包含’A’,’B’,’C’,所以是暗黑的字符串
你的任务就是计算出长度为n的字符串(只包含’A’、’B’和’C’),有多少个是暗黑的字符串。

输入描述:
输入一个整数n,表示字符串长度(1 ≤ n ≤ 30)

输出描述:
输出一个整数表示有多少个暗黑字符串

输入例子:
2
3

输出例子:
9
21


  • 递归
    时间复杂度太高了

递归代码如下:


#include <iostream>#include <vector>#include <string>#include <numeric>#include<algorithm>using namespace std;#define debug 0long long func(vector<char> str,int n){    if (str.size() == n)    {        return 1;    }    long long result(0);    if (str.size()==0)    {        result += func(vector<char>{'A', 'A'}, n);        result += func(vector<char>{'A', 'B'}, n);        result += func(vector<char>{'A', 'E'}, n);    }    else    {        auto iter = str.end();        auto iter_left = iter;        iter_left--;        auto iter_right = iter_left;        iter_right--;        int sum = 'A' + 'B' + 'E';        if ((*iter_left)+(*iter_right)+'A' != sum )        {            auto str_tmp = str;            str_tmp.push_back('A');            result += func(str_tmp,n);        }        if ((*iter_left) + (*iter_right) + 'B' != sum)        {            auto str_tmp = str;            str_tmp.push_back('B');            result += func(str_tmp, n);        }        if ((*iter_left) + (*iter_right) + 'E' != sum)        {            auto str_tmp = str;            str_tmp.push_back('E');            result += func(str_tmp, n);        }    }     return result; }int main(){    int n;    if (debug)    {        n = 3;    }    else    {        cin >> n;    }    vector<char> str;     cout<<3*func(str,n)<<endl;     return 0;}

  • 利用状态转换方程递推

两种状态的转移情况如下:S(i)状态添加的字符与最后两字符相等时,转化为S(i+1)状态,否则转化为D(i+1)状态;D(i)状态添加的字符与其最后字符相等时,转化为S(i)状态,与其倒数第二个字符相等时,转化为D(i+1)状态。状态转移方程如下:

S(n+1)=S(n)+D(n)

D(n+1)=2*S(n)+D(n)

注意:数字过大,需要long long类型防止溢出


#include <iostream>#include <vector>#include <string>#include <numeric>#include<algorithm>using namespace std;#define debug 0long long func(int n){    if (n==1)    {        return 3;    }    if (n==2)    {        return 9;    }    long long S = 3, D = 6, s, d;    for (auto k = 3; k <= n;++k)    {        s = S;        d = D;        S = s + d;        D = 2 * s + d;    }    return S + D;}int main(){    int n;    if (debug)    {        n = 3;    }    else    {        cin >> n;    }    cout<<func(n)<<endl;    return 0; }
原创粉丝点击