簡単 0件解決済み 正答率0%

Tribonacci

Return the nth tribonacci number, where each term is the sum of the three before it.

このチャレンジで学べること

  • Compute a sequence iteratively
  • Keep only the last few terms
  • Handle the starting terms directly

問題

翻訳を表示

The tribonacci numbers extend the Fibonacci idea to three terms: T(0) = 0, T(1) = 0, T(2) = 1, and from then on T(n) = T(n − 1) + T(n − 2) + T(n − 3). The sequence goes 0, 0, 1, 1, 2, 4, 7, 13, 24, 44, …

Implement tribonacci(n).

Input

n: The index of the term, starting at 0.

Output

Return T(n). Only the last three terms are needed at any time, so a loop with three variables is enough.

制約

0 ≤ n ≤ 74

例

例 1
入力:
n = 7

期待される出力:
expected = 13
入力:
long long n = 7;

期待される出力:
long long expected = 13;
入力:
long n = 7;

期待される出力:
long expected = 13;

解説

The terms are 0, 0, 1, 1, 2, 4, 7, 13, so T(7) = 13.

例 2
入力:
n = 2

期待される出力:
expected = 1
入力:
long long n = 2;

期待される出力:
long long expected = 1;
入力:
long n = 2;

期待される出力:
long expected = 1;

解説

T(2) is the first 1 in the sequence: 1.

解き方のヒント

まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。

ヒント 1

Return the first three terms directly.

ヒント 2

Keep three variables and shift them along each step.

ヒント 3

A recursive solution without memory repeats work and is far too slow.

目安の計算量

O(n) time, O(1) extra space

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

まだ合格した解答はありません。解いて 1 位になりましょう。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。