백준 - 12101 - 1, 2, 3 더하기 2

2021. 9. 9. 15:08Algorithm

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

 

12101번: 1, 2, 3 더하기 2

n을 1, 2, 3의 합으로 나타내는 방법 중에서 사전 순으로 k번째에 오는 것을 출력한다. k번째 오는 식이 없는 경우에는 -1을 출력한다.

www.acmicpc.net

 

import java.util.Scanner;

/**
 * 12101
 */
public class 일이삼더하기2 {
    private static int k;
    private static int count;
    private static String result = null;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String[] input = sc.nextLine().split(" ");
        int targetNumber = Integer.parseInt(input[0]);
        k = Integer.parseInt(input[1]);
        backtracking(targetNumber, 0, new StringBuilder());
        if (result == null) {
            System.out.println(-1);
        } else {
            System.out.println(result);
        }
    }

    private static void backtracking(int targetNumber, int sum, StringBuilder mathExpression) {
        if (sum == targetNumber) {
            count++;
            if (count == k) {
                result = mathExpression.substring(0, mathExpression.length() - 1);
            }
        } else if (sum > targetNumber) {
            return;
        }

        for (int i = 1; i <= 3; i++) {
            mathExpression.append(i+"+");
            backtracking(targetNumber, sum + i, mathExpression);
            mathExpression.delete(mathExpression.length() - 2, mathExpression.length());
        }
    }
}

알고리즘

백트래킹을 이용하여 1,2,3으로 특정 숫자를 만들기 위한 조합을 구현하였습니다.

순서가 사전순으로 정렬이 되어야하는데, 따로 정렬을 해줄 필요는 없습니다. 왜냐하면 이미 for문에서 1,2,3 순으로 완전탐색을 하고 있기 때문이에요, 그래서 몇 번째 수식인지만 체크해주면 됩니다^.^

'Algorithm' 카테고리의 다른 글

백준 - 9095 - 1, 2, 3 더하기  (0) 2021.09.09
백준 - 11725 - 트리의 부모 찾기  (0) 2021.09.07
백준 - 4963 - 섬의 개수  (0) 2021.09.07
백준 - 16926 - 배열 돌리기1  (0) 2021.04.07
백준 - 2776 - 암기왕  (0) 2021.03.30