티스토리 뷰

알고리즘

N-th Tribonacci Number (leetcode 1137)

뮹뭉묵목몽묭 2019. 8. 11. 13:54

The Tribonacci sequence Tn is defined as follows: 

T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.

Given n, return the value of Tn.

 

Example 1:

Input: n = 4 Output: 4 Explanation: T_3 = 0 + 1 + 1 = 2 T_4 = 1 + 1 + 2 = 4

Example 2:

Input: n = 25 Output: 1389537

 

Constraints:

  • 0 <= n <= 37
  • The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1.

트리보나치(n-2+n-1+n) 수를 구하는 문제이다. 주의사항으로는 n이 37까지이다.

 

본인의 경우 두가지 방법으로 풀어보았다.

첫번째 방법은 재귀 함수를 사용하지 않고 푼것이다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
    public int tribonacci(int n) {
        if (n < 2) {
        return n;
        }
        int a = 0, b = 1, c = 1, d;
//한칸씩 가면서 n까지 트리보나치를 구함
        while (n> 2) {
            d = a + b + c;
            a = b;
            b = c;
            c = d;
            n--;
        }
        return c;
    }
    
}
cs

다음 방법은 time exceed가 뜨나 재귀 함수를 이용해서 풀어볼려고 했던 방법이다.

 

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
    public int tribonacci(int n) { if(n==2||n==1) {
      return 1;
    } 
                                  if(n==0) {
         return 0;   
            }else {
        return tribonacci(n-1)+tribonacci(n-2)+tribonacci(n-3);
        }
                                  
    }
}
cs

최악의 경우 O(N^3)까지의 시간 복잡도를 가지고 있어서 time exceed가 뜨는 것 같다.

 

그래서 배열을 이용해서 다시 풀어 보았다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
    static int[] arr = new int[38];
    public int tribonacci(int n) {
        if(n == 0
            return 0;
        if(n == 1 ||== 2
            return 1;
        
        if(arr[n]!=0return arr[n];
        arr[n] = tribonacci(n-3)+tribonacci(n-2)+tribonacci(n-1);
        return arr[n];
    }
    
}
cs

배열에 있는 숫자의 경우 그냥 리턴하기 때문에 시간이 훨씬 줄어든다.

'알고리즘' 카테고리의 다른 글

Minimum Distance Between BST Nodes(leetcode 783) 문제  (0) 2019.08.13
Range of Sum BST (leetcode 938) 문제  (0) 2019.08.10
이진 트리란?  (0) 2019.08.09
재귀 함수란?  (0) 2019.08.09
큐(Queue)란?  (0) 2019.08.05
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함