본문 바로가기

[BAEKJOON] 2747번

<Java>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Scanner;
 
public class Main {
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n1 = 1;
        int n2 = 1;
        int n3 = n1 + n2;
        int n = sc.nextInt();
 
        for (int i = 3; i < n; ++i) {
            n1 = n2;
            n2 = n3;
            n3 = n1 + n2;
        }
 
        System.out.println((n2 == 1) ? (n/2 + n%2) : n3); 
 
        sc.close();
    }
}
cs


재귀함수는 시간초과 남.


특수한 입력값을 조건문으로 처리하기 싫어서 어떻게든 다르게 했는데 결국 별 다를 게 없게 됐다.

 n2 의 값이 초기값인 1로 유지되는 경우는 반복문 내에 진입하지 않는 경우 뿐이니 

 n = 1, 2, 3 인 경우다. 이 경우 출력값은 다음과 같다.


n = 1

=> n2 == 1: true

=> System.out.println(n/2 + n%2)

=> System.out.println(0 + 1)

=> System.out.println(1)


n = 2

=> n2 == 1: true

=> System.out.println(n/2 + n%2)

=> System.out.println(1 + 0)

=> System.out.println(1)


n = 3

=> n2 == 1: true

=> System.out.println(n/2 + n%2)

=> System.out.println(1 + 1)

=> System.out.println(2) 



특수한 입력값을 switch 문으로 처리하면 다음과 같다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.util.Scanner;
 
public class Main {
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        
        switch(n) {
        case 1case 2:
            System.out.println(1);
            break;
        default:        
            int n1 = 1;
            int n2 = 1;
            int n3 = n1 + n2;
                
            for(int i = 3; i < n; ++i) {
                n1 = n2;
                n2 = n3;
                n3 = n1 + n2;
            }
            System.out.println(n3); 
        }
        
        sc.close();
    }
}
cs



시간 초과로 인해 정답인지 확인할 수는 없지만 재귀함수로 풀면 다음과 같다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.Scanner;
 
public class Main {
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println(seq(sc.nextInt()));
        sc.close();
    }
    
    public static int seq(int n) {
        switch(n) {
        case 0case 1:
            return n;
        default:
            return (seq(n - 1+ seq(n - 2));
        }
    }
cs


'Programming > Solutions' 카테고리의 다른 글

[Project Euler] Problem 034  (0) 2021.01.11
[Project Euler] Problem 037  (0) 2019.07.25
[BAEKJOON] 15552번  (0) 2019.06.17
[BAEKJOON] 10828번  (0) 2019.06.17
[Project Euler] Problem 024  (0) 2019.05.19