Algorithm, Data structure/Solved Algorithmic Problem

BAEKJOON 1003 - 파보나치 함수

JaykayChoi 2016. 7. 10. 21:22

문제: https://www.acmicpc.net/problem/1003


파보나치를 구할 수 있는 재귀함수에서 0 과 1인 경우가 불리는 횟수는 나열을 해보면

0의 경우 주어진 n - 1 의 파보나치 수

1의 경우 주어진 n 의 파보나치 수와 같다는 것을 알 수 있습니다.

그리고 파보나치 수의 경우 n이 커지면 시간복잡도가 매우 커지기 때문에 memoization 을 사용해 시간 복잡도를 줄여 풀었습니다.



my solving

c++

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
32
33
34
35
36
37
38
39
40
41
#include <fstream>
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
 
map<intint> cache;
int fibonacci_dp(int num)
{
    map<intint>::iterator it = cache.find(num);
    if (it != cache.end())
        return it->second;
 
    int ret = 0;
    if (num == 0)
        ret = 0;
    else if (num == 1)
        ret = 1;
    else
        ret = fibonacci_dp(num - 1+ fibonacci_dp(num - 2);
 
    cache.insert(make_pair(num, ret));
 
    return ret;
}
 
int main()
{
    int cases;
    cin >> cases;
    for (int i = 0; i < cases; i++)
    {
        int n;
        cin >> n;
        if (n == 0)
            cout << "1 0" << endl;
        else
            cout << fibonacci_dp(n - 1<< " " << fibonacci_dp(n) << endl;
    }
    return 0;
}
cs


'Algorithm, Data structure > Solved Algorithmic Problem' 카테고리의 다른 글

BAEKJOON 1005 - ACM Craft  (0) 2016.07.13
BAEKJOON 1004 - 어린왕자  (0) 2016.07.12
BAEKJOON 1002 - 터렛  (0) 2016.07.10
USACO 2.2 - Party Lamps  (0) 2016.07.09
USACO 2.2 - Runaround Numbers  (0) 2016.07.08