Algorithm/문제풀이
[Leetcode] 1137. N-th Tribonacci Number 문제 풀이
bluespacedev
2021. 9. 24. 16:38
https://leetcode.com/problems/n-th-tribonacci-number/
N-th Tribonacci Number - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제 내용
피보나치 수열처럼 3개를 더한 값을 다음으로 쓰는 수열에서 N 번째 수 구하기
Example 1:
Input: n = 4
Output: 4
Explanation:
T_3 = 0 + 1 + 1 = 2
T_4 = 1 + 1 + 2 = 4
문제 풀이
단순히 반복문을 돌리면 된다.
대입하는 것을 최소화 하기 위해서 로테이션으로 저장하는 방법을 이용했다.
class Solution {
public:
int tribonacci(int n) {
int t[3] = {0, 1, 1};
for (int i = 3; i <= n; ++i) {
t[i%3] = t[0] + t[1] + t[2];
}
return t[n%3];
}
};