코딩테스트 문제풀이
[프로그래머스] 위장 - HashMap
지잉지잉
2021. 9. 10. 10:32
1. 문제
2. 풀이
import java.util.*;
class Solution {
public int solution(String[][] clothes) {
int answer = 1;
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < clothes.length; i++) {
String item = clothes[i][0];
String category = clothes[i][1];
Integer categoryCount = map.get(category);
if (categoryCount == null) categoryCount = 0;
categoryCount++;
map.put(category, categoryCount);
}
Iterator<String> keys = map.keySet().iterator();
while(keys.hasNext()) {
String key = keys.next();
answer *= (map.get(key) + 1);
}
return answer - 1 ;
}
}
- category 별로 item의 갯수를 hashMap에 저장한다.
- 모든 경우의 수는 (특정 category의 아이템 갯수 + 1)를 모두 곱한 값 - 1이다.
- 이 때, 아이템 갯수에 1을 더하는 이유는 안입는 경우가 있으므로.
- 모두 곱한 값에 -1을 하는 이유는 모두 안입는 경우를 제외해야 하므로. (최소 한가지의 아이템은 착용해야한다.)
출처: https://programmers.co.kr/learn/courses/30/lessons/42578