알고리즘/acmicpc

[백준][15654번]N과 M(5)[JAVA]

장그래 2021. 4. 13. 15:31
반응형

문제 설명

N개의 자연수와 자연수 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오. N개의 자연수는 모두 다른 수이다.

  • N개의 자연수 중에서 M개를 고른 수열

풀이 방법

  • 주어진 N개의 배열을 갖고 순열을 만들면 되는 문제였다.
  • N과M(1)번 문제와 유사했고, N의 원소에 대해 값을 꺼내고, 중복 체크를 해주면 되는 문제이다.

알아야되는 개념

  • 백트래킹
  • Stringbuilder
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    static int N, M;
    static int arr[] = new int[10];
    static boolean check[] = new boolean[10001];
    static int num[];
    static StringBuilder sb = new StringBuilder();
    static void func(int depth){
        if (depth == M){
            for(int i=0;i<M;i++){
                sb.append(arr[i] + " ");
            }
            sb.append("\n");
            return;
        }
        else {
            for (int i = 0; i <N; i++) {
                int temp = num[i];
                if(check[temp]) continue;
                check[temp] = true;
                arr[depth] = num[i];
                func(depth + 1);
                check[temp] = false;
            }
        }
    }
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());
        st = new StringTokenizer(br.readLine());

        num = new int[N];
        for(int i=0;i<N;i++){
            num[i] = Integer.parseInt(st.nextToken());
        }
        Arrays.sort(num);
        func(0);
        System.out.print(sb);
    }
}
반응형