본문 바로가기

카테고리 없음

[JAVA] 프로그래머스[해시level2] 위장

문제 설명

스파이들은 매일 다른 옷을 조합하여 입어 자신을 위장합니다.

예를 들어 스파이가 가진 옷이 아래와 같고 오늘 스파이가 동그란 안경, 긴 코트, 파란색 티셔츠를 입었다면 다음날은 청바지를 추가로 입거나 동그란 안경 대신 검정 선글라스를 착용하거나 해야 합니다.

종류이름

얼굴 동그란 안경, 검정 선글라스
상의 파란색 티셔츠
하의 청바지
겉옷 긴 코트

스파이가 가진 의상들이 담긴 2차원 배열 clothes가 주어질 때 서로 다른 옷의 조합의 수를 return 하도록 solution 함수를 작성해주세요.

제한사항

  • clothes의 각 행은 [의상의 이름, 의상의 종류]로 이루어져 있습니다.
  • 스파이가 가진 의상의 수는 1개 이상 30개 이하입니다.
  • 같은 이름을 가진 의상은 존재하지 않습니다.
  • clothes의 모든 원소는 문자열로 이루어져 있습니다.
  • 모든 문자열의 길이는 1 이상 20 이하인 자연수이고 알파벳 소문자 또는 '_' 로만 이루어져 있습니다.
  • 스파이는 하루에 최소 한 개의 의상은 입습니다.

입출력 예

clothesreturn

[["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개의 조합이 가능합니다.

1. yellow_hat 2. blue_sunglasses 3. green_turban 4. yellow_hat + blue_sunglasses 5. green_turban + blue_sunglasses

예제 #2
face에 해당하는 의상이 crow_mask, blue_sunglasses, smoky_makeup이므로 아래와 같이 3개의 조합이 가능합니다.

1. crow_mask 2. blue_sunglasses 3. smoky_makeup

 

문제 풀이

조합 문제로 해석하여, 문제를 해결하려고 하였더니 1번 유형에서 시간초과가 발생하였다.

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class prepareTest3 {
    private static int numOfClothType;
    private static int answer = 0;
    private static int[] info;

    public static void main(String[] args) {
        String[][] clothes = {{"yellowhat", "headgear"}, {"bluesunglasses", "eyewear"}, {"green_turban", "headgear"}};

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

        numOfClothType = map.keySet().size();
        info = new int[numOfClothType];

        int index = 0;
        for (String clothType: map.keySet()) {
            int numOfCloth = map.get(clothType);
            info[index] = numOfCloth;
            index ++;
        }

        for (int i = 1; i < numOfClothType + 1; i++) {
            permutationTest3(0, 0, i, 1, numOfClothType);
        }
        System.out.println(answer);
    }
    private static void permutationTest3(int index, int start, int end, int sum, int target) {
        if (index == end) {
            answer += sum;
            return;
        }

        for (int i = start; i < target; i++) {
            sum *= info[i];
            permutationTest3(index + 1, i + 1, end, sum, target);
            sum /= info[i];
        }
    }

}

 

String[][] clothes = {{"yellowhat", "headgear"}, {"bluesunglasses", "eyewear"}, {"green_turban", "headgear"}};

 

1가지 조합 : 2 + 12가지 조합: 2 * 1결과: 3 + 2

위와 같은 방식으로 기존에 문제를 해결하려 했다면 아래 코드는

( 2 + 1 ) * ( 1 + 1) - 1 = 5

와 같이 해결하였다.

 

모든 옷은 입는다 안 입는다로 귀결되고, 모두 안 입을 경우의 수를 빼주면 ( - 1) 결과 값을 도출할 수 있다.

 

 

 

import java.util.*;

public class prepareTest3 {


    public static void main(String[] args) {
        String[][] clothes = {{"yellowhat", "headgear"}, {"bluesunglasses", "eyewear"}, {"green_turban", "headgear"}};

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

        List<Integer> list = new ArrayList<>();
        for (String clothType: map.keySet()) {
            list.add(map.get(clothType));
        }

        int answer = list.stream().reduce(1, (a, b) -> a * (b + 1)) - 1;
    }
}