알고리즘/acmicpc

[백준][15655번]N과 M(6)[JAVA]

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

문제 설명

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

  • N개의 자연수 중에서 M개를 고른 수열
  • 고른 수열은 오름차순이어야 한다.

풀이 방법

  • N과M(5)번 문제와, N과M(4)번 문제의 결합 문제이다.
  • 주어진 N을 이용해서 순열을 만들지만, N배열이 정렬되어 있다는 가정으로 매개변수의 idx를 1씩 증가하면 된다.

알아야되는 개념

  • 백트래킹
  • 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, int idx){
if (depth == M){
for(int i=0;i<M;i++){
sb.append(arr[i] + " ");
}
sb.append("\n");
return;
}
else {
for (int i = idx; i < N; i++) {
int temp = num[i];
if(check[temp]) continue;
check[temp] = true;
arr[depth] = num[i];
func(depth + 1, i+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,0);
System.out.print(sb);
}
}
반응형