Baekjoon algorithm training

[백준] 1003 (피보나치 함수)

interfacer_han 2023. 10. 26. 19:00

#1 알고리즘

#1-1

 

동적 프로그래밍 (Dynamic Programming), 상향식(Bottom-up) 및 하향식(Top-down) 접근

#1 알고리즘 동적 프로그래밍을 한 줄 요약하면 중복의 제거다. 정적(static)이라는 개념과 반대되는 개념으로서, 동적(dynamic)이라는 이름을 붙었다. 확실히 static이 붙을 만한 작업은 아니지만, 그

kenel.tistory.com

하향식 동적 프로그래밍을 구현해 풀었다.

 

#1-2

 

#1-3

 

#2 코드

#2-1 자바

import java.util.*;

public class Main {
    public static Map<Integer, Integer[]> map = new HashMap<>();
    
    public static void main(String[] args) {
        Integer[] seedData0 = {1, 0};
        Integer[] seedData1 = {0, 1};
        map.put(0, seedData0);
        map.put(1, seedData1);
        
        Scanner sc = new Scanner(System.in);
        String loopCountStr =  sc.nextLine().trim();
        int loopCount = Integer.parseInt(loopCountStr);
        
        for(int i = 0; i < loopCount; i++) {
            String testCaseStr =  sc.nextLine().trim();
            int testCase = Integer.parseInt(testCaseStr);
         
            Integer[] result = fibonacci(testCase);
            System.out.println(Integer.toString(result[0]) + " " + Integer.toString(result[1]));
        }   
    }
    
    public static Integer[] fibonacci(int n) {
        Integer[] result = {0, 0};
        
        if(map.containsKey(n)) { // 캐싱(메모) 되어있는지 확인
            Integer[] cachedData = map.get(n);
            result[0] += cachedData[0];
            result[1] += cachedData[1];
           
        } else {
            result[0] += fibonacci(n-1)[0] + fibonacci(n-2)[0];
            result[1] += fibonacci(n-1)[1] + fibonacci(n-2)[1];
            map.put(n, result);
        }
        
        return result;
    }
}

 

#2-2 코틀린

val map = HashMap<Int, Array<Int>>()

fun main() {
    val seedData0 : Array<Int> = arrayOf(1, 0)
    val seedData1 : Array<Int> = arrayOf(0, 1)
    map.put(0, seedData0)
    map.put(1, seedData1)
    
    val loopCount = readLine()!!.trim().toInt()
    
    for(i : Int in 1..loopCount) {
        val testCase = readLine()!!.trim().toInt()
        
        val result = fibonacci(testCase)
        println(result[0].toString() + " " + result[1].toString())
    }
}

fun fibonacci(n : Int) : Array<Int> {
    var result : Array<Int> = arrayOf(0, 0)
    
    if(map.containsKey(n)) { // 캐싱(메모) 되어있는지 확인
        val cachedData = map.get(n)
        result[0] += cachedData!![0]
        result[1] += cachedData!![1]
        
    } else {
        result[0] += fibonacci(n-1)[0] + fibonacci(n-2)[0]
        result[1] += fibonacci(n-1)[1] + fibonacci(n-2)[1]
        map.put(n, result)
    }
    
    return result
}

'Baekjoon algorithm training' 카테고리의 다른 글

[백준] 1436 (영화감독 숌)  (0) 2023.11.03
[백준] 1157 (단어 공부)  (0) 2023.10.31
[백준] 1181 (단어 정렬)  (0) 2023.10.28
[백준] 1018 (체스판 다시 칠하기)  (0) 2023.10.27
[백준] 1002 (터렛)  (0) 2023.10.25