less than 1 minute read

Updated:

문제 설명

  • 스파이들은 매일 다른 옷을 조합해 입어 자신을 위장한다.
  • 스파이가 가진 의상들이 담긴 2차원 배열 clothes가 주어질 때 서로 다른 옷의 조합의 수를 return 하도록 solution 함수를 작성하라.

구현 순서

Map을 이용하여 각 옷의 종류별 개수를 계산하고, 이를 바탕으로 경우의 수를 계산한다.

  • 같은 종류의 옷이 여러 개 있을 때, 해당 종류의 옷을 입지 않는 경우를 추가로 고려한다.
  • 모든 종류의 옷을 입지 않는 경우는 고려하지 않는다.
  • 각 종류별 옷의 개수가 n1, ,n2,… nk일 때 경우의 수는 (n1+1)(n2+1)…-1이다.

구현 코드 1

import java.util.*;

class Solution {
    public int solution(String[][] clothes) {

        Map<String, Integer> clothesMap = new HashMap<>();
        for(String[] cloth : clothes){
            String type = cloth[1];
            clothesMap.put(type, clothesMap.getOrDefault(type, 0) + 1);
        }

        int answer = 1;
        for(int cnt : clothesMap.values()){
            answer *= (cnt + 1);
        }
        return answer-1;
    }
}

구현코드 2

  • 람다식으로 리팩토링
  • 경우의 수 계산하는 반복문은 answer가 상수가 아니면 사용할 수가 없어서 람다식으로 변경 가능한 방법이 있는지는 더 고민해보려한다.
import java.util.*;

class Solution {
    public int solution(String[][] clothes) {

        Map<String, Integer> clothesMap = new HashMap<>();
        Arrays.stream(clothes).forEach(cloth -> {
            String type = cloth[1];
            clothesMap.put(type, clothesMap.getOrDefault(type, 0) + 1);
        });

        int answer = 1;
        for(int cnt : clothesMap.values()){
            answer *= (cnt + 1);
        }
        return answer-1;
    }
}