10974번
문제
- N이 주어졌을 때, 1부터 N까지의 수로 이루어진 순열을 사전순으로 출력하는 프로그램을 작성하시오.
문제 해결 순서
- 그냥 통째로 외우자...
- depth를 인자로 받는 permutation 함수를 하나 선언
- depth 가 N일 경우에 출력
- 아닐때 N만큼 반복하며 i번째 방문 -> 방문한 숫자 출력배열에 저장 -> depth + 1 해서 재귀 호출 -> i번째 방문 해제
- 4번에 4가지 스텝만 외우면 됨.
import java.util.Scanner;
class Main {
static int N;
static int arr[];
static int out[];
static boolean visit[];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
arr = new int[N];
out = new int[N];
visit = new boolean[N];
for(int i = 0; i < N; i++) {
arr[i] = i+1;
}
permutation(0);
}
public static void permutation(int depth) {
if(depth == N) {
for(int i = 0; i < N; i++) {
System.out.print(out[i]+ " ");
}
System.out.println();
}
for(int i = 0; i < N; i++) {
if(!visit[i]) {
visit[i] = true;
out[depth] = arr[i];
permutation(depth+1);
visit[i] = false;
}
}
}
}