https://www.acmicpc.net/problem/1003
정답률 33.439%
다음 소스는 N번째 피보나치 수를 구하는 C++ 함수이다.
int fibonacci(int n) {
if (n == 0) {
printf("0");
return 0;
} else if (n == 1) {
printf("1");
return 1;
} else {
return fibonacci(n‐1) + fibonacci(n‐2);
}
}
fibonacci(3)을 호출하면 다음과 같은 일이 일어난다.
1은 2번 출력되고, 0은 1번 출력된다. N이 주어졌을 때, fibonacci(N)을 호출했을 때, 0과 1이 각각 몇 번 출력되는지 구하는 프로그램을 작성하시오.
3
0
1
3
1 0
0 1
1 2
피보나치 수열은 다음과 같고
첫 번째와 두 번째 수는 1이고, N번째 부터는 N-1번째와 N-2번째 수를 더한 값이 된다.
문제는 피보나치 수의 0과 1이 호출 되는 횟수를 구해야 하는데 동적 계획법으로 풀기위해 다음과 같이 0과 1의 호출 횟수를 저장하는 메모제이션 배열을 생성한다.
Integer[][] dp = new Integer[41][2];
//초기값 설정
dp[0][0] = 1;
dp[0][1] = 0;
dp[1][0] = 0;
dp[1][1] = 1;
그리고 재귀 함수를 생성하는데 숫자 N의 0과 1의 호출 횟수가 저장되지 않았을 경우 재귀를 호출한다.
static Integer[] recur(int N) {
if (dp[N][0] == null || dp[N][1] == null) {
dp[N][0] = recur(N - 1)[0] + recur(N - 2)[0];
dp[N][1] = recur(N - 1)[1] + recur(N - 2)[1];
}
return dp[N];
}
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
//백준
public class Main {
static Integer[][] dp;
public static void main(String[] args) throws IOException {
System.setIn(new FileInputStream("src/input.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
dp = new Integer[41][2];
dp[0][0] = 1;
dp[0][1] = 0;
dp[1][0] = 0;
dp[1][1] = 1;
StringBuilder sb = new StringBuilder();
for (int testCase = 0; testCase < T; testCase++) {
int N = Integer.parseInt(br.readLine());
sb.append(recur(N)[0])
.append(" ")
.append(recur(N)[1])
.append("\n");
}
System.out.println(sb);
}
static Integer[] recur(int N) {
if (dp[N][0] == null || dp[N][1] == null) {
dp[N][0] = recur(N - 1)[0] + recur(N - 2)[0];
dp[N][1] = recur(N - 1)[1] + recur(N - 2)[1];
}
return dp[N];
}
}