微软笔试编程题 求多少个子序列符合斐波那契排列

本文介绍了一种算法,用于计算给定序列中有多少非空子序列是斐波那契数列的前缀。通过递归方法生成所有可能的子序列,并检查这些子序列是否符合斐波那契数列的定义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

描述
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;
}

测试结果
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值