[프로그래머스] 후보키

이재윤·2025년 1월 28일

https://school.programmers.co.kr/learn/courses/30/lessons/42890

1) 코드

uniqueList = [] 

def checkUnique(arr, relation):
    
    selected = set()
    
    for row in relation:
        newRow = ""
        for col in arr:
            newRow += row[col]
        if newRow in selected:
            return False 
        else:
            selected.add(newRow)

    return True 


## 2^8 = 256이다 
def dfs(pos, total, arr, relation):

    if pos == total:
        if len(arr) != 0:
            result = checkUnique(arr, relation)
            if result == True:
                arrNums = ""
                for num in arr:
                    arrNums += str(num)
                uniqueList.append(arrNums)
        return 
    
    arr.append(pos)
    dfs(pos+1, total, arr, relation)
    arr.pop()
    dfs(pos+1, total, arr, relation)
    
    
def solution(relation):
    answer = 0
    
    
    total = len(relation[0])
    
    arr = [] 
    dfs(0, total, arr, relation)
    
    sorted_uniqueList = sorted(uniqueList, key=len)
    
    answer = []
    
    for i in range(len(sorted_uniqueList)):
        curr = sorted_uniqueList[i]
        addable = True
        for j in range(len(answer)):
            tmp = answer[j] 
            if all(char in curr for char in tmp):
                addable = False
                break 
            
        if addable == True:
            answer.append(curr)
                
    return len(answer)

2) 해설

  • Uniqueness와 Minimality를 잘 판단해야 하는 문제이다
  • if all(char in curr for char in tmp) 문법을 잘 기억해도록 하자
  • sorted(uniqueList, key=len) 문법도 잘 기억해도록 하자

0개의 댓글