코딩 교훈 기록

파이썬 알고리즘 문제 시간 초과 해결하는 방법

Disciple428 2024. 2. 23. 17:44
  1. input 대신 sys.stdin.readline 쓰기!
  2. 언어 pypy3 써보기!
  3. for 문이나 재귀 함수, 'if A in B' 등이 많이 쓰이거나 함께 쓰이면 배열을 전부 검사하면서 소요시간이 급증한다! 따라서 필요한 만큼의 공간을 갖고 있는 리스트를 만들어두고 인덱스를 활용하거나 중복을 피하기 위한 변수를 따로 설정해서 중복되는 조합을 피하는 것에 활용할 수 있다.
import sys
input = sys.stdin.readline

def pick(M):
    if M == 0:
        print(*result)
        return
    flag = 0
    for n in range(N):
        if index_record[n] == 0 and flag != arr[n]:
            result.append(arr[n])
            index_record[n] = 1
            flag = arr[n]
            pick(M-1)
            result.pop()
            index_record[n] = 0

N, M = map(int, input().split())    # 자연수, 고를 개수
arr = list(map(int, input().split()))   # N개의 자연수 리스트
arr.sort()
result = []
index_record = [0] * N
pick(M)