[백준] 10870번 : 피보나치 수 5

letsbebrave·2021년 12월 17일
0

codingtest

목록 보기
12/146

문제

느낀점

리스트에 넣고 앞에 두 개의 값을 더해주는 식으로 결과값을 저장해주었다. 재귀를 어떻게 써야 할지 고민을 더 해봐야 할 것 같다.

풀이

import java.util.Scanner;

public class Main
{
	public static void main(String[] args) {
	    
	    Scanner sc = new Scanner(System.in);
	    
	    int num = sc.nextInt();
	    int[] result = new int[num + 1];
	    
	    if (num == 0){
	        result[0] = 0;  
	    } 
	    
	    if (num == 1){
	        result[1] = 1;
	    }
	    
	    if (num >= 2) {
	        	result[0] = 0;   
	            result[1] = 1;
	        for (int i = 2; i <= num; i++){
    	        result[i] = result[i-1] + result[i-2]; 
	        }
	    }
	    
	    System.out.println(result[num]);
	    
	}
}
profile
그게, 할 수 있다고 믿어야 해

1개의 댓글

comment-user-thumbnail
2021년 12월 19일

재귀를 사용해서 피보나치를 구현할 수 있습니다.
저는
public static int fibonacci(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
return fibonacci(n-2) + fibonacci(n-1);
}

이렇게 피보나치 값을 구하는 재귀함수를 사용했는데,
본문에 작성하신대로 for문을 사용해도 성능이나 시간복잡도는 차이가 없을 것 같네요 ㅎㅎ

답글 달기