[알고리즘] Permutation(순열)

Permutation(순열)

순열이란 n 개의 값 중에서 r 개의 숫자를 모든 순서대로 뽑는 경우를 말함

ex) [1,2,3]일 때 크기가 3인 배열에서 2개를 뽑았을 때 [1, 2] [1, 3] [2, 1] [2, 3] [3, 1] [3, 2] 6가지의 경우가 나온다.

Swap을 이용한 순열

// 순서 없이 n 개중에서 r 개를 뽑는 경우
// 사용 예시: permutation(arr, 0, n, 4);
static void permutation(int[] arr, int depth, int n, int r) {
    if(depth == r) {
        print(arr, r);
        return;
    }
 
    for(int i=depth; i<n; i++) {
        swap(arr, depth, i);
        permutation(arr, depth + 1, n, r);
        swap(arr, depth, i);
    }
}
 
static void swap(int[] arr, int depth, int i) {
    int temp = arr[depth];
    arr[depth] = arr[i];
    arr[i] = temp;
}

 // 배열 출력
    static void print(int[] arr, int r) {
        for(int i=0; i<r; i++)
            System.out.print(arr[i] + " ");
        System.out.println();
    }

//결과
1 2 3
1 3 2
2 1 3
2 3 1
3 2 1
3 1 2

visited 배열을 이용한 순열

// 순서를 지키면서 n 개중에서 r 개를 뽑는 경우
// 사용 예시: perm(arr, output, visited, 0, n, 3);
static void perm(int[] arr, int[] output, boolean[] visited, int depth, int n, int r) {
    if(depth == r) {
        print(output, r);
        return;
    }
 
    for(int i=0; i<n; i++) {
        	/*************************************** 

			여기서 visited 배열을 사용하지 않으면 중복 순열이 가능하다
					
			 *******************************************/
        if(visited[i] != true) {
            visited[i] = true;
            output[depth] = arr[i];
            perm(arr, output, visited, depth + 1, n, r);       
            output[depth] = 0; // 이 줄은 없어도 됨
            visited[i] = false;;
        }
    }
}

//결과
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

문제

백준 10974

정리된 코드

Permutation_Last