• 문제 링크
10974번: 모든 순열
N이 주어졌을 때, 1부터 N까지의 수로 이루어진 순열을 사전순으로 출력하는 프로그램을 작성하시오.
www.acmicpc.net
• 풀이 과정
• 풀이 코드
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class Main {
static int n;
static int[] arr;
static boolean[] visit;
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
n = Integer.parseInt(br.readLine());
arr = new int[n];
visit = new boolean[n];
recur(0);
bw.write(sb.toString());
bw.flush();
}
private static void recur(int depth) {
if (depth == n) {
for (int i = 0; i < n; i++)
sb.append(arr[i]).append(" ");
sb.append("\n");
return;
}
for (int i = 0; i < n; i++) {
if (visit[i])
continue;
arr[depth] = i + 1;
visit[i] = true;
recur(depth + 1);
visit[i] = false;
}
}
}
'Problem Solving > Baekjoon' 카테고리의 다른 글
[백준] 10597 순열장난 - Backtracking / Java (0) | 2023.02.23 |
---|---|
[백준] 2992 크면서 작은 수 - Backtracking / Java (0) | 2023.02.22 |
[백준] 1448 삼각형 만들기 - Greedy / Java (0) | 2023.02.20 |
[백준] 1105 팔 - Greedy / Java (0) | 2023.02.19 |
[백준] 19939 박 터뜨리기 - Greedy / Java (0) | 2023.02.18 |
댓글