본문 바로가기

algorithm/프로그래머스

프로그래머스_위장(C++, JAVA)

 

programmers.co.kr/learn/courses/30/lessons/42578

 

코딩테스트 연습 - 위장

 

programmers.co.kr

[문제 풀이]

Map을 이용하여 문제를 풀었습니다.

 

이 문제는 서로 다른 의상의 종류를 선택해 나올 수 있는 모든 경우의 수를 찾는 문제 였습니다. 문제를 풀기 위해 Map에 의상의 종류의 개수를 저장해 줍니다. 그 후 의상의 개수를 곱해서 경우의 수를 구하고 아무것도 입지 않은 경우를 빼줍니다. 

[C++]

#include <string>
#include <vector>
#include<map>
#include<set>
#include<iostream>

using namespace std;

map<string, int> spy;

int solution(vector<vector<string>> clothes) {
    int answer = 1;
    
    for(int i = 0; i < clothes.size(); i++){
        string str = clothes[i][1];
        
        if(spy.find(str) == spy.end())
            spy[str] = 1;
        else
            spy[str]++;
    }
    
    for(auto item : spy)
       answer *=  item.second + 1;
    
    
    return answer - 1;
}

 

[JAVA]

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

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