개발자-H 입니다.

BOJ - 좋은 수열 본문

Algorithm/문제 풀이

BOJ - 좋은 수열

개발자-H 2021. 9. 23. 16:43

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

 

2661번: 좋은수열

첫 번째 줄에 1, 2, 3으로만 이루어져 있는 길이가 N인 좋은 수열들 중에서 가장 작은 수를 나타내는 수열만 출력한다. 수열을 이루는 1, 2, 3들 사이에는 빈칸을 두지 않는다.

www.acmicpc.net

 

  • 주어진 좋은 수열을 만족하는 경우에만 123 탐색을 진행했다.
  • 123 중복을 허용하는 순으로 진행했기 때문에 가장 작은 수는 가장 첫 번째 발견되는 수열이다.

 

import java.io.*;

public class Main {

    private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    private static char[] words = new char[]{
            '1', '2', '3'
    };

    public static void main(String[] args) throws IOException {
        int N = Integer.parseInt(br.readLine());
        dp(0, "", N);
    }

    private static void dp(int depth, String combination, int length) {
        if (combination.length() == length) {
            if (isValid(combination)) {
                System.out.println(combination);
                System.exit(0);
            }
            return;
        }

        for (int i = 0; i < words.length; i++) {
            if (!isValid(combination)) continue;
            dp(depth + 1, combination + words[i], length);
        }
    }

    private static boolean isValid(String combination) {
        if (combination.length() == 1) return true;

        for (int length = 1; length <= combination.length() / 2; length++) {
            for (int i = 0; i <= combination.length() - length * 2; i++) {
                String front = combination.substring(i, i + length);
                String rear = combination.substring(i + length, i + length + length);
                if (front.equals(rear)) {
                    return false;
                }
            }
        }

        return true;
    }
}

'Algorithm > 문제 풀이' 카테고리의 다른 글

BOJ - 모든 순열  (0) 2021.09.25
BOJ - 차이를 최대로  (0) 2021.09.24
BOJ - 선발 명단  (0) 2021.09.23
BOJ - 암호 만들기  (0) 2021.09.22
BOJ - 색종이 붙이기  (0) 2021.09.21
Comments