본문 바로가기
Algorithm/Programmers

프로그래머스 42578번 위장

by eurowondollaryen 2022. 7. 26.

문제

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

풀이

이 문제를 한 마디로 요약하면, 옷 종류별 조합의 갯수를 구하는 것이다.(부위별로 안 입는 경우 포함, 모두 안 입을 수 없음)

풀이 순서는 아래와 같다.

1. HashMap을 이용하여 옷 종류별로 개수 카운트 - O(n)

2. 옷 종류별로 조합의 수를 계산 - O(4) (최악의 경우 옷의 종류는 4종이므로)

import java.util.HashMap;
class Solution {
    public int solution(String[][] clothes) {
		int answer = 1;
        //옷 종류별 가짓수
		HashMap<String, Integer> clothesCount = new HashMap<String, Integer>();
		for(int i = 0; i < clothes.length; ++i) {
            if(clothesCount.get(clothes[i][1]) != null) {
                clothesCount.put(clothes[i][1], clothesCount.get(clothes[i][1]) + 1);
            } else {
                clothesCount.put(clothes[i][1], 1);
            }
        }
        for(String key : clothesCount.keySet()) {
            answer *= clothesCount.get(key)+1;//옷 종류 안 입는 경우 1 추가
        }
        
        return answer-1;//아무것도 안 입는 경우 제외
	}
}