순열(Permutation) 예제
2025. 4. 8. 11:34
import java.util.Arrays;

public class Permutation1 {
	public static void permute(int[] arr, int depth, int n) {
		if (depth == n) {
			System.out.println(Arrays.toString(arr)); // 순열 출력
			System.out.println();
			return;
		}
		for (int i = depth; i < n; i++) {
			System.out.println("SWAP depth="+depth+ ", i="+ i);
			swap(arr, depth, i);
			permute(arr, depth + 1, n);
			swap(arr, depth, i); // 원상 복구
		}
	}

	private static void swap(int[] arr, int i, int j) {
		int temp = arr[i];
		arr[i] = arr[j];
		arr[j] = temp;
	}

	public static void main(String[] args) {
		int[] arr = { 1, 2, 3 };
		permute(arr, 0, arr.length);
	}
}

'코딩테스트' 카테고리의 다른 글

SubSet(부분집합)  (0) 2025.04.08
Combination(조합)  (0) 2025.04.08
순열(Permutation)  (0) 2025.04.08
백준 11659번 - 구간 합 구하기  (0) 2025.04.07
백준 11382번 - 꼬마 정민  (0) 2025.04.07