Post

[BaekJoon] 2748번 - 피보나치 수 2 [Java][C++]

[BaekJoon] 2748번 - 피보나치 수 2 [Java][C++]

문제 링크


1. 문제 풀이


피보나치 수열에서 $n$ 번째 수를 구하는 문제로 주어진 점화식을 활용한 다이나믹 프로그래밍으로 해결할 수 있다.


2. 코드


1. 풀이 [Java]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int N = Integer.parseInt(br.readLine());

        long[] dp = new long[1 + N];
        dp[1] = 1;
        for (int i = 2; i <= N; i++) {
            dp[i] = dp[i - 1] + dp[i - 2];
        }

        System.out.println(dp[N]);
    }
}


2. 풀이 [C++]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <bits/stdc++.h>
using namespace std;

constexpr int MAXN = 90;

long long dp[1 + MAXN] = {0, 1};

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    cin >> n;

    for (int i = 2; i <= n; i++) {
        dp[i] = dp[i - 1] + dp[i - 2];
    }

    cout << dp[n];
}

This post is licensed under CC BY 4.0 by the author.