-
[Leetcode] 1137. N-th Tribonacci Number 문제 풀이Algorithm/문제풀이 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]; } };
'Algorithm > 문제풀이' 카테고리의 다른 글
[Leetcode] 929. Unique Email Addresses 문제 풀이 (0) 2021.09.27 [Leetcode] Shortest Path in a Grid with Obstacles Elimination 문제 풀이 (0) 2021.09.25 [Leetcode] 572. Subtree of Another Tree 문제 풀이 (0) 2021.09.22 [Leetcode] 117. Populating Next Right Pointers in Each Node II 문제 풀이 (0) 2021.09.22 [Leetcode] 547. Number of Provinces 문제 풀이 (0) 2021.09.22