[Algorithm/java] 위장

Jay·2020년 12월 18일
0

Algorithm

목록 보기
7/44
post-thumbnail

문제 설명

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

예를 들어

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

종류 : 이름
얼굴 : 동그란 안경, 검정 선글라스
상의 : 파란색 티셔츠
하의 : 청바지
겉옷 : 긴 코트
스파이가 가진 의상들이 담긴 2차원 배열 clothes가 주어질 때 서로 다른 옷의 조합의 수를 return 하도록 solution 함수를 작성해주세요.

제한사항

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

입출력 예

clothes : [[yellow_hat, headgear], [blue_sunglasses, eyewear], [green_turban, headgear]]
return : 5

clothes : [[crow_mask, face], [blue_sunglasses, face], [smoky_makeup, face]]
return : 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

접근하기

  • [의상의 이름, 의상의 종류] 와 같은 형태로 존재함으로 우선 for문으로 큰 배열의 길이를 구해서 answer에 더한다. (최소 1개의 조합이니까 하나씩 묶일 수도 있다.)
  • 의상의 종류 갯수를 구해서 의상의 종류를 A개라고 한다면 A개의 조합인 A!를 answer에 더해서 리턴한다.

1차시도

import java.util.*;

class Solution {
    public int solution(String[][] clothes) {
        int answer = 0;
        List<String> list = new ArrayList<String>();
        int result = 1;
         
        //1. 최소 1개씩일 경우, 더하기
        answer += clothes.length;
        
        //2. 종류 갯수 찾기 위해서 중복 제거 리스트 만들기
        for(int i=0; i<clothes.length; i++){
            if(!list.contains(clothes[i][1])){
                list.add(clothes[i][1]);
            }        
        }
        
        //3. 중복 제거된 리스트의 크기로 팩토리얼 구하기.
        if(list.size()>1){
            for(int j=list.size(); j>0; j--){
                result *= j;
            }        
            answer += result;
        }
    
        return answer;
    }
}

패배...

2차시도

import java.util.*;

class Solution {
    public int solution(String[][] clothes) {
        int answer = 0;
        int result = 1;
        HashMap<String,Integer> list = new HashMap<String,Integer>();
         
        //1. 최소 1개씩일 경우, 더하기
        answer += clothes.length;
        
        //2. 종류 갯수 찾기 위해서 중복 제거 리스트 만들기
        for(int i=0; i<clothes.length; i++){
            
            if(list.containsKey(clothes[i][1])){ //중복값이 있다면
                int updateNum = list.get(clothes[i][1]) + 1;
                list.put(clothes[i][1],updateNum);            
            }       
            
            else if(!list.containsKey(clothes[i][1])){//새로운 값이라면        
                list.put(clothes[i][1],1);                           
            }
        }    
        
        if(list.size()>1){
            for(int i=0; i<list.size(); i++){            
                result *= list.get(clothes[i][1]);
                System.out.println(result); 
            }    
            answer += result;
        }
    
        return answer;
    }
}

3차시도

  • 결국 hashmap을 더 찾고 나서야 성공했다.
import java.util.*;

class Solution {
    public int solution(String[][] clothes) {
        int answer = 1;
        
        HashMap<String,Integer> list = new HashMap<String,Integer>();
         
        for(int i=0; i<clothes.length; i++){
            String key = clothes[i][1];
            if(!list.containsKey(key)){
                list.put(key, 1);
            }else{
                list.put(key, list.get(key)+1);
            }
        }        
        
        Iterator<Integer> it = list.values().iterator();
        
        while(it.hasNext()){                    
            answer *= it.next().intValue()+1;            
        }
        
        return answer-1;
    }
}

📌 KeyNote

  • 처음엔 배열로 접근하려 했는데 키-값 형태가 제일 접근하기 편하기에 HashMap을 생각해야 했다.
  • Iterator로 해쉬맵내의 데이터 값들을 팩토리얼 형태로 곱해서 저장.
profile
developer

0개의 댓글