줄 서는 방법

최민수·2023년 8월 1일
1

알고리즘

목록 보기
78/94
import math

temp, answer = [], []

def simulate(n, k):
    global temp, answer
    comp = math.factorial(n-1)

    if n == 1:
        answer.append(temp.pop())
        return
    
    q = k // comp
    r = k % comp
    k -= (q*comp)
    
    if r > 0:
        q += 1
    item = temp[q-1]
    answer.append(item)
    del temp[q-1]

    simulate(n-1, k)
        

def solution(n, k):
    global answer, temp
    
    temp = [i for i in range(1,n+1)]
    simulate(n,k)

    return answer

LV 2

순열(permutation) 을 돌리거나 백트래킹(dfs) 를 쓸 경우, 최악의 경우 20! 를 연산해야 될 수 있다.
이렇게 되면 무조건 시간초과다.

따라서 앞자리 수를 계속 결정해나가면서 k를 줄여나가야겠다고 생각했다.

(n-1)! 을 기준으로 몫과 나머지를 계산해서 앞자리 숫자를 결정할 수 있다.
이런 식으로 1-n 까지의 숫자 모두가 결정될 때까지 반복해주면 쉽게 답을 구할 수 있다.


출처: https://school.programmers.co.kr/learn/courses/30/lessons/12936

profile
CS, 개발 공부기록 🌱

0개의 댓글