10이하의 N개의 자연수가 주어지면 이 중 M개를 뽑아 일렬로 나열하는 방법을 모두 출력하는 프로그램
import java.util.Scanner;
public class Main {
static int n, m;
static int[] arr, answer, ch;
public static void DFS(int level) {
if (level==m) {
for (int x : answer) {
System.out.print(x + " ");
}
System.out.println();
}
else {
for (int i=0; i<n; i++) {
if (ch[i]==0) {
ch[i] = 1; // 사용한 경우 // 1
answer[level] = arr[i];
DFS(level+1);
ch[i] = 0; // 체크 해제 // 0
}
}
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt(); // 자연수의 개수
m = scanner.nextInt(); // 뽑을 개수
arr = new int[n]; // n개의 자연수 // 오름차순으로 주어짐
for (int i=0; i<n; i++) {
arr[i] = scanner.nextInt();
}
answer = new int[m]; // 뽑은 수 배열
ch = new int[n]; // 중복 방지 // 뽑았던 수인지 확인
DFS(0);
}
}
3 2
3 6 9
3 6
3 9
6 3
6 9
9 3
9 6
댓글