줄 서는 방법n!개의 수중 k번째의 배열을 출력하시오 본문

카테고리 없음

줄 서는 방법n!개의 수중 k번째의 배열을 출력하시오

violet4795 2019. 8. 1. 13:41

n이 3이라면 

1,2,3

1,3,2

2,1,3

2,3,1

3,1,2

3,2,1

6가지 중 k = 5 라면 3,1,2를 출력하면된다.

 

n <= 20  , k <= n! 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public int[] solution(int n, long k){
        //전체경우의수는 n!
        long all = 1;
        long maruta = k-1;
        int[] answer = new int[n];
        ArrayList<Integer> abcd = new ArrayList<Integer>();
        long[] facNum = new long[n];
        for(int i = 0; i < n; i++) {
            abcd.add(i+1);
        }
        for(int i = 1; i <= n; i++) {
            all *= i;
            facNum[i-1= all;
        }
        int moc = 0;
        int j = 0
        for(int i = n-1; i >= 1; i--) {
            moc = (int) (maruta / facNum[i-1]);
            maruta = (int) (maruta % facNum[i-1]);
            answer[j++= abcd.remove(moc);
        }
        answer[j++= abcd.remove(0);
        return answer;
    }
cs