---
# System prepended metadata

title: 1137. N-th Tribonacci Number
tags: [Leetcode]

---

<style>
    html, body, .ui-content {
    background: #222222;
    color: #00BFFF;
}
    /* 設定 code 模板 */
    .markdown-body code,
.markdown-body tt {
    background-color: #ffffff36;
}
.markdown-body .highlight pre,
.markdown-body pre {
    color: #ddd;
    background-color: #00000036;
}
.hljs-tag {
    color: #ddd;
}
.token.operator {
  background-color: transparent;
}    
/* 設定連結 */
a,
.open-files-container li.selected a {
    color: #89FFF8;
    
}
a:hover,
.open-files-container li.selected a:hover {
    color: #89FFF890;
}
   
</style>

###### tags: `Leetcode`

# 1137. N-th Tribonacci Number

###### Link : https://leetcode.com/problems/n-th-tribonacci-number/description/

## 題目
回傳Tribonacci Number的第n項
## 程式碼 I
vector version
```cpp=
class Solution {
public:
    int tribonacci(int n) {
        if(n == 0 || n == 1) return n;
        else if(n == 2) return 1;
        vector<int> tri(n+1);
        int last = 3;
        tri[0] = 0, tri[1] = 1, tri[2] = 1;
        while(last <= n){
            tri[last] = tri[last - 3] + tri[last - 2] + tri[last-1];
            ++last;
        }
        return tri[n];
    }
};
```
## 程式碼 II
陣列版本 faster than vector
```cpp=
class Solution {
public:
    int tribonacci(int n) {
        if(n == 0 || n == 1) return n;
        else if(n == 2) return 1;
        int tri[n+1], last = 3;
        tri[0] = 0, tri[1] = 1, tri[2] = 1;
        while(last <= n){
            tri[last] = tri[last - 3] + tri[last - 2] + tri[last-1];
            ++last;
        }
        return tri[n];
    }
};
```
## Date 
### 2023/1/30