백준 - 15665 - N과 M(11)

2021. 3. 9. 15:21Algorithm

www.acmicpc.net/problem/15665

 

15665번: N과 M (11)

한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다. 수열은 사전 순으로 증가하는 순서로 출력해

www.acmicpc.net

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Scanner;
import java.util.Set;

/**
 * 백준 15665
 * 순열
 */
public class N과_M_11 {
    private static int N;
    private static int[] array;
    private static Set<String> set = new LinkedHashSet<>();

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String[] inputs = sc.nextLine().split(" ");
        N = Integer.parseInt(inputs[0]);
        int M = Integer.parseInt(inputs[1]);
        array = new int[N+1];
        String[] nums = sc.nextLine().split(" ");
        for(int i=1; i<=N; i++) {
            array[i] = Integer.parseInt(nums[i-1]);
        }
        Arrays.sort(array);
        printPermutation(M, "");
        for (String str : set) {
            System.out.println(str);
        }
    }

    private static void printPermutation(int M, String str) {
        if(M == 0) {
            set.add(str.trim());
            return;
        }

        for(int i=1; i<array.length; i++) {
            printPermutation(M - 1, str + " " + array[i]);
        }
    }
}

문제

  • 주어진 배열에서 중복이 있는 순열
  • 하지만 결과는 중복될 수 없다.

 

알고리즘

  • 백트래킹, 순열
  • 자신 중복 체크를 한다
  • 결과 중복 체크를 위해 LinkedHashSet을 이용하였다. 중복을 제거해주고 순서를 유지시켜주는 자료구조.

'Algorithm' 카테고리의 다른 글

백준 - 14888 - 연산자 끼워넣기  (0) 2021.03.10
백준 - 15666 - N과 M(12)  (0) 2021.03.09
백준 - 15664 - N과 M(10)  (0) 2021.03.09
백준 - 15663 - N과 M(9)  (0) 2021.03.09
백준 - 15657 - N과 M(8)  (0) 2021.03.09