描述
Given a sequence {an}, how many non-empty sub-sequence of it is a prefix of fibonacci sequence.
A sub-sequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
The fibonacci sequence is defined as below:
F1 = 1, F2 = 1
Fn = Fn-1 + Fn-2, n>=3
输入
One line with an integer n.
Second line with n integers, indicating the sequence {an}.
For 30% of the data, n<=10.
For 60% of the data, n<=1000.
For 100% of the data, n<=1000000, 0<=ai<=100000.
输出
One line with an integer, indicating the answer modulo 1,000,000,007.
样例提示
The 7 sub-sequences are:
{a2}
{a3}
{a2, a3}
{a2, a3, a4}
{a2, a3, a5}
{a2, a3, a4, a6}
{a2, a3, a5, a6}
样例输入
6
2 1 1 2 2 3
样例输出
7
思路:递归解决,递归方法求出所有的子序列,然后比较子序列是否满足斐波那契排列。递归的方法是循环去掉容器中n个元素,剩下的是子序列(1 = < n < = size)。当去掉n个元素时,先去掉一个,然后递归调用函数再去掉n-1个。直到n-1==0,判断该子序列是否为斐波那契排列。
代码:
#include <iostream>
#include <vector>
using namespace std;
#define N 1000000007
vector<int> Fibonacci;
int max = 0;
bool IsFibonacci(vector<int> & source, vector<int> Fib)
{
for (auto i = source.begin(), start = Fib.begin(); i != source.end(); ++i, ++start)
{
if (*i != *start)
return false;
}
return true;
}
void GetSubArrayAndJudgeFibonacci(vector<int> source,int x,int begin)
{
if (x == 0)
{
if (IsFibonacci(source, Fibonacci))
{
++max;
max %= N;
}
return;
}
for (int i = begin; i < source.size(); ++i)
{
auto copy = source;
copy.erase(copy.begin() + i);
GetSubArrayAndJudgeFibonacci(copy, x - 1,i);
}
}
int main(int argc, char *argv[])
{
Fibonacci.push_back(1);
Fibonacci.push_back(1);
for (int i = 2; i < 26; ++i)
{
Fibonacci.push_back(Fibonacci[i - 2] + Fibonacci[i-1]);
}
int num,temp;
vector<int> ivec;
cin >> num;
for (int i = 0; i < num; ++i)
{
cin >> temp;
ivec.push_back(temp);
}
int size = ivec.size();
for (int i = 0; i < size; ++i) //i代表去掉几个元素
{
GetSubArrayAndJudgeFibonacci(ivec, i, 0);
}
cout << max;
return 0;
}
测试结果