[백준 10974 자바] 순열

일단 해볼게·2023년 3월 21일
0

백준

목록 보기
107/132

https://www.acmicpc.net/problem/10974

import java.io.*;

public class Main {
    public static int N;
    public static int[] arr;
    public static boolean[] visited;
    public static StringBuilder sb = new StringBuilder();

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        N = Integer.parseInt(br.readLine());
        arr = new int[N]; 
        visited = new boolean[N]; // 방문 여부를 나타내는 배열

        permutation(0);
        System.out.println(sb);
    }

    public static void permutation(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(visited[i])
                continue;

            arr[depth] = i + 1; 
            visited[i] = true;
            permutation(depth + 1);
            visited[i] = false;
        }
    }
}

처음에는 이해가 안갔는데 그림을 보고 디버깅하면 이해하기 수월하다.

참고
https://humansight.tistory.com/99

profile
시도하고 More Do하는 백엔드 개발자입니다.

0개의 댓글