[ 문제 ]
N이 주어졌을 때, 1부터 N까지의 수로 이루어진 순열을 사전순으로 출력하는 프로그램을 작성하시오.
[ 입력 ]
- 첫째 줄에 N(1 ≤ N ≤ 8)이 주어진다.
[ 출력 ]
- 첫째 줄부터 N!개의 줄에 걸쳐서 모든 순열을 사전순으로 출력한다.
[ 입력 예제 ]
3
[ 출력 예제 ]
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
import java.util.Scanner;
public class Main {
static int N;
public static void permutation (int cnt, boolean[] isSelected, int[] output) {
if (cnt == N) {
for (int i = 0; i < N; i++) System.out.print(output[i] + " ");
System.out.println();
return;
}
for (int i = 0; i < N; i++) {
if (isSelected[i]) continue;
output[cnt] = i + 1;
isSelected[i] = true;
permutation(cnt + 1, isSelected, output);
isSelected[i] = false;
}
}
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
N = scanner.nextInt();
boolean[] isSelected = new boolean[N];
int[] output = new int[N];
permutation(0, isSelected, output);
scanner.close();
}
}
'Algorithm > 백준+프로그래머스+SWEA+정올+구름' 카테고리의 다른 글
[Algorithm] 백준 3052 나머지 (0) | 2021.08.22 |
---|---|
[Algorithm] 백준 3985 롤 케이크 (0) | 2021.08.22 |
[Algorithm] 백준 1780 종이의 개수 (0) | 2021.08.22 |
[Algorithm] 백준 2630 색종이 만들기 (0) | 2021.08.22 |
[Algorithm] 백준 8958 OX퀴즈 (0) | 2021.08.22 |