Algorithm/알아두면 좋은 템플릿 코드

[Permutation] 순열 템플릿 코드

생각없이 해도 생각보다 좋다. 2023. 6. 17. 13:04
import java.util.Arrays;
import java.util.Scanner;

/*
    총 개수: N
    뽑는 개수: R
    isSelected를 사용함으로써 사용 체크 및 순열의 형태의 경우의 수를 만들어냄
*/
public class Permutation {
    static int N, R, totalCnt;
    static int[] totals, selected;
    static boolean[] isSelected;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        N = sc.nextInt();
        R = sc.nextInt();
        totals = new int[N];
        selected = new int[R];
        isSelected = new boolean[N];
        for (int i = 0; i < N; i++) {
            totals[i] = i+1;
        }

        permu(0);
        System.out.println(totalCnt);
    }

    private static void permu(int cnt) {
        if(cnt == R){
            totalCnt++;
            System.out.println(Arrays.toString(selected));
            return;
        }
        for (int i = 0; i < N; i++) {
            if(!isSelected[i]){
                isSelected[i] = true;
                selected[cnt] = totals[i];
                permu(cnt+1);
                isSelected[i] = false;
            }
        }
    }
}