【codewars-19】斐波那契的变种问题

Well met with Fibonacci bigger brother, AKA Tribonacci.

As the name may already reveal, it works basically like a Fibonacci, but summing the last 3 (instead of 2) numbers of the sequence to generate the next. And, worse part of it, regrettably I won’t get to hear non-native Italian speakers trying to pronounce it 😦

So, if we are to start our Tribonacci sequence with [1, 1, 1] as a starting input (AKA signature), we have this sequence:

[1, 1 ,1, 3, 5, 9, 17, 31, …]
But what if we started with [0, 0, 1] as a signature? As starting with [0, 1] instead of [1, 1] basically shifts the common Fibonacci sequence by once place, you may be tempted to think that we would get the same sequence shifted by 2 places, but that is not the case and we would get:

[0, 0, 1, 1, 2, 4, 7, 13, 24, …]
Well, you may have guessed it by now, but to be clear: you need to create a fibonacci function that given a signature array/list, returns the first n elements - signature included of the so seeded sequence.

Signature will always contain 3 numbers; n will always be a non-negative number; if n == 0, then return an empty array (except in C return NULL) and be ready for anything else which is not clearly specified 😉

分析
此题目和斐波那契类似, 输入是数组的前三个元素, 每个元素是前3个元素之和, 唯一麻烦的地方是要返回N个元素的数组. 麻烦之处在于可能要要求返回小于三个元素的数组.

要点

  • vector.erase(.begin() ) 实现vector的pop_front
  • std::accumulate() + 反向迭代器 实现总是对数组最后三个元素求和.
#include <algorithm>
#include <numeric>
#include <vector>
std::vector<int> tribonacci(std::vector<int> signature, int n)
{
  std::vector<int> result{};
  while(result.size()< static_cast<size_t >(n) ){
    if(signature.size() > 0)
    {
      result.push_back(signature.front());
      signature.erase(signature.begin()); //插入后将输入数组中的删除
    } 
    else 
    {
      result.push_back( std::accumulate(result.rbegin(), result.rbegin()+3, 0 , [](int a , int b){return a+b;} )); 
      // 用反向迭代器对后三个元素求和. 
    }
  }
  return result;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值