알고리즘/동적 프로그래밍

[BOJ 2193] 이친수 (Java, DP)

leejinwoo1126 2023. 7. 10. 11:31
반응형

 


문제 링크 

https://www.acmicpc.net/problem/2193

 

2193번: 이친수

0과 1로만 이루어진 수를 이진수라 한다. 이러한 이진수 중 특별한 성질을 갖는 것들이 있는데, 이들을 이친수(pinary number)라 한다. 이친수는 다음의 성질을 만족한다. 이친수는 0으로 시작하지 않

www.acmicpc.net


문제 풀이 

- 시간복잡도 : O(N)

- 점화식 DP[N] = DP[N - 2] + DP[N - 1] 형태로 최대 N이 90까지 가능하다

- 피보나치의 경우 46번째만 넘어가도 29억이 넘기 때문에 long (8byte, 64bit)으로 문제 풀이 해야 함

 

풀이 순서
가짜 문제 정의 - 가짜 문제로 정답을 구할 수 있는가? - 초기항 - 점화식 - 풀이 & 테스트
0 1 2 3 4
0 1 10 100
101
1000
1010
1001

- 초기항의 경우 DP[0] = 0, DP[1] = 1로 해준다 

- DP[N - 1] 숫자에 대해 뒤에 '0'을 붙이고, DP[N - 2]에 대해 뒤에 '01'을 붙이게 되면 중복 없이 숫자 구할 수 있다

 

 


제출 코드 

 

(1) Bottom-Up방식 

import java.util.*;
import java.io.*;

public class Main {
    
    static int N;

    static long[] DP;

    static void input() throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        N = Integer.parseInt(br.readLine());
        DP = new long[N + 1];
    }

    static void executeBottomUp() {
        DP[0] = 0;
        DP[1] = 1;

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

    public static void main(String[] args) throws Exception {
        input();
        executeBottomUp();

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

 

(2) Top-Down 방식

import java.util.*;
import java.io.*;

public class Main {
    
    static int N;

    static long[] DP;

    static void input() throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        N = Integer.parseInt(br.readLine());
        
        DP = new long[N + 1];
        
        Arrays.fill(DP, -1);
        DP[0] = 0L;
        DP[1] = 1L;
    }

    static long topDown(int idx) {
        if(idx == 0 || idx == 1) return DP[idx];

        if(DP[idx] != -1) return DP[idx];

        return DP[idx] = topDown(idx - 2) + topDown(idx - 1);
    }

    public static void main(String[] args) throws Exception {
        input();

        System.out.println(topDown(N));
    }
}
반응형