आसान 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

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 के लिए अनुकूलित की गई है। ऊपर दिए गए स्टेटमेंट और सीमाओं का पालन करें।

हर कोडर का सबसे अच्छा पास हुआ समाधान। तेज़, कम मेमोरी वाले और बेहतर रेटिंग वाले समाधान ऊपर रहते हैं।

अभी कोई पास हुआ समाधान नहीं है। इसे हल करें और पहला स्थान पाएँ।

दूसरों से सीखें

समुदाय समाधान

अभी तक कोई प्रकाशित समाधान नहीं। पहला साझा करने के लिए इस चुनौती को हल करें।