반응형
15657번: N과 M (8)
N개의 자연수와 자연수 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오. N개의 자연수는 모두 다른 수이다. N개의 자연수 중에서 M개를 고른 수열
www.acmicpc.net
조금만 변형하면 풀리는 문제
import java.util.*;
public class Main {
static int N, M;
static int[] num;
static int[] print;
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
M = sc.nextInt();
num = new int[N];
print = new int[M];
for (int i=0; i<N; i++) num[i] = sc.nextInt();
Arrays.sort(num);
bt(0, 0);
System.out.print(sb);
}
static void bt(int depth, int start){
if (depth == M){
for (int i : print)
sb.append(i+" ");
sb.append("\n");
return;
}
for (int i=start; i<N; i++){
print[depth] = num[i];
bt(depth + 1, i);
}
}
}
반응형
'Algorithm' 카테고리의 다른 글
백준 10807번 개수 세기 [ Java ] (0) | 2020.12.25 |
---|---|
백준 10808번 알파벳 개수 [ Java ] (0) | 2020.12.25 |
백준 15656번 N과 M (7) [ Java ] (0) | 2020.12.23 |
백준 15655번 N과 M (6) [ Java ] (0) | 2020.12.23 |
백준 15654번 N과 M (5) [ Java ] (0) | 2020.12.23 |