본문 바로가기

알고리즘/프로그래머스

[프로그래머스 코딩테스트 고득점 Kit / 해시] 의상 (python)

728x90

풀이

def solution(clothes):
    answer = 1
    dict_clothes = {}
    
    for i in range(len(clothes)):
        if clothes[i][1] in dict_clothes:
            dict_clothes[clothes[i][1]] += 1
        else:
            dict_clothes[clothes[i][1]] = 1
    
    for i in dict_clothes.values():
        answer *= i+1
    
    answer -= 1
        
    return answer

내 풀이

clothes return
[["yellow_hat", "headgear"], ["blue_sunglasses", "eyewear"], ["green_turban", "headgear"]] 5
[["crow_mask", "face"], ["blue_sunglasses", "face"], ["smoky_makeup", "face"]] 3
      첫번째 케이스의 경우 headgear: 2개, eyewear: 1개임.

각 의상 별로 경우의 수는,

headgear는 xx / ox / xo   -> 3가지 (oo는 안됨. 같은 의상을 두 개 걸칠 수 없으므로)

eyewear는 o / x                -> 2가지

각 경우의 수를 곱하면 6. 여기서 모두 안입는 경우 (xx x)를 빼주면 6-1 = 5가 됨.

각 의상 종류 별로 n+1C1 (n은 각 의상 종류 별 의상 개수) 의 경우의 수가 나옴. 이렇게 나온 값을 다 곱해주고 마지막에 -1을 하면됨.

따라서 이를 알고리즘으로 구현하면 아래와 같음.

  1. dict에 의상 종류별로 저장 (key - 의상 종류, value - 개수)
  2. dict 돌면서 answer *= (value + 1) 실행.
  3. 마지막으로 모든 옷을 안 걸친 경우를 제외하기 위해 answer -= 1
반응형