반응형
문제 설명
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); } }
반응형
'알고리즘 > acmicpc' 카테고리의 다른 글
[백준][19236번]청소년 상어[JAVA] (0) | 2021.04.16 |
---|---|
[백준][20055번]컨베이어 벨트 위의 로봇[JAVA] (0) | 2021.04.13 |
[백준][15654번]N과 M(5)[JAVA] (0) | 2021.04.13 |
[백준][15652번]N과 M(4)[JAVA] (0) | 2021.04.13 |
[백준][15651번]N과 M(3)[JAVA] (0) | 2021.04.13 |