최대 1 분 소요

Question

Q Q2


Solution

  • clothes에 있는 의상들을 map<string, int>로 의상의 종류를 key로 받아 저장한다.
  • 이미 있는 key라면 수량을 증가시킨다.
  • 옷 종류에 따른 수식은 (x + a)(x + b)(x + n)… -1 와 같이 된다.
    x는 의상의 종류고 a, b, …n은 상수이다. 위 식을 풀어낸 마지막은 x^n이 남기 때문에 -1을 해줘야 한다.

Cord

#include <string>
#include <vector>
#include <unordered_map>

using namespace std;

int solution(vector<vector<string>> clothes)
{
    unordered_map<string, int> kinds;
    int answer = 1;

    // 의상의 종류별로 몇개인지 넣기
    for (int i = 0; i < clothes.size(); i++)
    {
        // key가 없다면 추가
        if (kinds.find(clothes[i][1]) == kinds.end())
        {
            kinds.insert({ clothes[i][1], 1 });
        }
        // key가 이미 있다면 수량 증가 
        else
        {
            kinds[clothes[i][1]]++;
        }
    }

    // 옷 종류에 따른 수식 (x + a)(x + b)(x + n)... - 1
    // -1 은 (의상 종류인 x의 승수에 대한 값이 무의미 하기 때문)
    for (auto it = kinds.begin(); it != kinds.end(); it++)
    {
        answer *= (1 + it->second);
    }

    return answer - 1;
}

Result

Result