[프로그래머스 고득점 Kit] 위장 C++ 문제 풀이

반응형
반응형

#INFO

난이도 : LEVEL2

출처 : https://school.programmers.co.kr/learn/courses/30/lessons/42578

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


#SOLVE

2차원 벡터 clothes 에 [의상 이름, 의상 종류] 정보가 저장됩니다.

<string,int> type unordered_map을 하나 선언해 준 뒤, for 반복문으로 clothes 벡터를 순회하며 key (string) 에는 의상 종류를 value (int) 에는 의상 종류의 수를 저장합니다.

    int answer = 1;
    unordered_map<string, int> clothes_map;
    for(int i = 0; i < clothes.size(); ++i){
        clothes_map[clothes[i][1]]++;
    }

 

clothes에 저장된 정보가 다음과 같다면

[["yellow_hat", "headgear"], ["blue_sunglasses", "eyewear"], ["green_turban", "headgear"]]

 

clothes_map 에는 아래와 같이 저장되어 있을 것 입니다.

headgear : 2

eyewear : 1

 

그럼 이제 나올 수 있는 모든 경우의 수를 계산해 보면

headgear를 착용하는 경우의 수 2가지 + headgear를 착용하지 않는 경우의 수 1가지 = 3가지 

eyewear를 착용하는 경우의 수 1가지 + eyewear를 착용하지 않는 경우의 수 1가지 = 2가지

위의 경우의 수를 모두 곱해준 뒤 clothes를 아무 것도 착용하지 않는 경우 1가지를 빼주면 정답은

3 * 2 -1 = 5가 return 됩니다. 

위 과정을 코드로 표현하면 다음과 같습니다.

    unordered_map<string, int>::iterator it;
    for(it = clothes_map.begin(); it != clothes_map.end(); ++it){
        answer *= it -> second + 1;
    }
    // clothes를 하나도 착용하지 않는 경우
    answer--;

#CODE

#include <string>
#include <vector>
#include <unordered_map>
using namespace std;

int solution(vector<vector<string>> clothes) {
    int answer = 1;
    unordered_map<string, int> clothes_map;
    for(int i = 0; i < clothes.size(); ++i){
        clothes_map[clothes[i][1]]++;
    }
    unordered_map<string, int>::iterator it;
    for(it = clothes_map.begin(); it != clothes_map.end(); ++it){
        answer *= it -> second + 1;
    }
    answer--;
    return answer;
}
반응형

댓글

Designed by JB FACTORY