위장
문제 설명
스파이들은 매일 다른 옷을 조합하여 입어 자신을 위장합니다.
예를 들어 스파이가 가진 옷이 아래와 같고 오늘 스파이가 동그란 안경, 긴 코트, 파란색 티셔츠를 입었다면 다음날은 청바지를 추가로 입거나 동그란 안경 대신 검정 선글라스를 착용하거나 해야 합니다.
종류 이름
얼굴 동그란 안경, 검정 선글라스
상의 파란색 티셔츠
하의 청바지
겉옷 긴 코트
스파이가 가진 의상들이 담긴 2차원 배열 clothes가 주어질 때 서로 다른 옷의 조합의 수를 return 하도록 solution 함수를 작성해주세요.
제한사항
clothes의 각 행은 [의상의 이름, 의상의 종류]로 이루어져 있습니다.
스파이가 가진 의상의 수는 1개 이상 30개 이하입니다.
같은 이름을 가진 의상은 존재하지 않습니다.
clothes의 모든 원소는 문자열로 이루어져 있습니다.
모든 문자열의 길이는 1 이상 20 이하인 자연수이고 알파벳 소문자 또는 '_' 로만 이루어져 있습니다.
스파이는 하루에 최소 한 개의 의상은 입습니다.
입출력 예
clothes return
[["yellowhat", "headgear"], ["bluesunglasses", "eyewear"], ["green_turban", "headgear"]] 5
[["crowmask", "face"], ["bluesunglasses", "face"], ["smoky_makeup", "face"]] 3
입출력 예 설명
예제 #1
headgear에 해당하는 의상이 yellow_hat, green_turban이고 eyewear에 해당하는 의상이 blue_sunglasses이므로 아래와 같이 5개의 조합이 가능합니다.
yellow_hat
blue_sunglasses
green_turban
yellow_hat + blue_sunglasses
green_turban + blue_sunglasses
예제 #2
face에 해당하는 의상이 crow_mask, blue_sunglasses, smoky_makeup이므로 아래와 같이 3개의 조합이 가능합니다.
crow_mask
blue_sunglasses
smoky_makeup
def solution(clothes_list):
clothes_dict = {}
for clothes_name, clothes_type in clothes_list:
if clothes_type in clothes_dict.keys():
clothes_dict[clothes_type] += 1
else:
clothes_dict[clothes_type] = 1
count = 1
for value in clothes_dict.values():
count *= (value + 1)
return count - 1
예전에 풀었던 문제인데 도저히 푸는 방법이 생각이 안나서 3중 for문으로 풀었더니 테스트 1번이 시간초과가 발생했다. (ㅠㅠ)
주어진 옷 정보를 카운트하여 어떤 종류의 옷이 각각 몇개있는지 파악한다. 예제 1번을 예시로 들면 clothes_kind_count_list는 [2, 1]이다. 옷의 종류가 총 2개 존재하므로 1개를 뽑았을 때의 경우의 수, 2개를 뽑았을 때의 경우의 수를 모두 합하여 출력한다.
from collections import defaultdict, Counter
from itertools import combinations
def solution(clothes):
answer = 0
clothes_kind_count = defaultdict(int)
for name, kind in clothes:
clothes_kind_count[kind] += 1
clothes_kind_count_list = clothes_kind_count.values()
# 의상의 수는 최소 1개 이상이므로 의상이 없는 경우는 따로 처리하지 않음
for i in range(1, len(clothes_kind_count.keys()) + 1):
combinations_list = combinations(clothes_kind_count_list, i)
for j, combination in enumerate(combinations_list):
temp = 1
for c in combination:
temp *= c
answer += temp
return answer
왜..돌아갔지...
도저히 모르겠어서 이전에 풀었던 코드를 참고했다. 시간초과가 발생한 코드는 가능한 경우의 수를 다 카운트
하여 더하였고 이전 코드는 모든 경우의 수 중에서 조건에 있던 '최소 하나의 옷은 입는다'를 이용하여 아무것도 입지 않은 경우를 하나 빼서 출력
한다.
from collections import defaultdict
def solution(clothes):
answer = 1
clothes_kind = defaultdict(int)
for name, kind in clothes:
clothes_kind[kind] += 1
for count in clothes_kind.values():
answer *= (count + 1)
return answer - 1
경우의 수 문제라면 각각의 경우의 수를 더하는 것이 더 빠른지 전체 경우의 수에서 조건에 걸린 일부만 제외하는 것이 더 빠른지 유의하자.