728x90
[Silver III] 피보나치 함수 - 1003
성능 요약
메모리: 13004 KB, 시간: 116 ms
분류
다이나믹 프로그래밍(dp)
문제 설명
다음 소스는 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)
을 호출하면 다음과 같은 일이 일어난다.
fibonacci(3)
은fibonacci(2)
와fibonacci(1)
(첫 번째 호출)을 호출한다.fibonacci(2)
는fibonacci(1)
(두 번째 호출)과fibonacci(0)
을 호출한다.- 두 번째 호출한
fibonacci(1)
은 1을 출력하고 1을 리턴한다. fibonacci(0)
은 0을 출력하고, 0을 리턴한다.fibonacci(2)
는fibonacci(1)
과fibonacci(0)
의 결과를 얻고, 1을 리턴한다.- 첫 번째 호출한
fibonacci(1)
은 1을 출력하고, 1을 리턴한다. fibonacci(3)
은fibonacci(2)
와fibonacci(1)
의 결과를 얻고, 2를 리턴한다.
1은 2번 출력되고, 0은 1번 출력된다. N이 주어졌을 때, fibonacci(N)
을 호출했을 때, 0과 1이 각각 몇 번 출력되는지 구하는 프로그램을 작성하시오.
입력
첫째 줄에 테스트 케이스의 개수 T가 주어진다.
각 테스트 케이스는 한 줄로 이루어져 있고, N이 주어진다. N은 40보다 작거나 같은 자연수 또는 0이다.
출력
각 테스트 케이스마다 0이 출력되는 횟수와 1이 출력되는 횟수를 공백으로 구분해서 출력한다.
풀이
N | 0의 개수 | 1의 개수 |
0 | 1 | 0 |
1 | 0 | 1 |
2 | 1 | 1 |
3 | 1 | 2 |
4 | 2 | 3 |
5 | 3 | 5 |
이렇게 표를 작성하다 보면 0과 1의 개수 또한 피보나치 수열을 이루고 있음을 확인할 수 있다.
fib(5) = fib(4) + fib(3) 이기 때문에
fib(4)에서 출력되는 0,1 의 횟수와 fib(3)에서 출력되는 0, 1의 횟수를 더한 것이 fib(5)의 0, 1의 횟수가 된다.
package BOJ.Silver.s3;
import java.util.Scanner;
public class BOJ_1003_피보나치함수 {
public static void main(String[] args) {
int[][] dp = new int[41][2];
dp[0][0] = 1;
dp[1][1] = 1;
for (int i = 2; i <= 40; i++) {
dp[i][0] = dp[i - 1][0] + dp[i - 2][0];
dp[i][1] = dp[i - 1][1] + dp[i - 2][1];
}
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
StringBuilder sb = new StringBuilder();
for (int t = 0; t < T; t++) {
int i = sc.nextInt();
sb.append(dp[i][0]);
sb.append(" ");
sb.append(dp[i][1]).append("\n");
}
System.out.print(sb);
}
}
728x90
'문제 풀이 > BOJ' 카테고리의 다른 글
[백준] 14503 - 로봇 청소기 (자바 Java) (0) | 2022.10.06 |
---|---|
[백준] 16236 - 아기 상어 (자바 Java) (0) | 2022.10.06 |
[백준] 2096 - 내려가기 (자바 Java) (0) | 2022.10.06 |
[백준] 2293 - 동전 1, 2294 - 동전 2 (자바 Java) (1) | 2022.10.05 |
[백준] 7682 - 틱택토 (자바 Java) (0) | 2022.10.05 |