본문 바로가기

C#/알고리즘 문제 풀기

프로그래머스 - 의상 조합 (해시 셋)

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

 

 

이번 문제는 중복된 의상 없이 조합을 맞추는 문제로 풀 수 있는 방법이 여러가지 존재하고 접근법 또한 엄청 방대한 문제라고 생각했다.

 

따라서 오랫만에 한동안 써보지 않은 해시 셋 기능을 활용해서, 의상 리스트의 종류 개수를 해시에 저장하고 각각의 종류를 key 값으로 가지고 종류의 개수를 int 형 value로 가지는 딕셔너리를 활용하여 문제를 풀었다.

 

 


 

 

 

public int solution(string[,] clothes)
{
    int answer = 1;
    HashSet<string> types = new HashSet<string>(); // 옷의 종류
    Dictionary<string, int> typeCount = new Dictionary<string, int>(); // 옷 종류별 개수

    for(int i = 0; i < clothes.GetLength(0); i++)
    {
        string type = clothes[i, 1];
        types.Add(type);
        
        if (typeCount.ContainsKey(type))
        {
            typeCount[type]++;
        }
        else
        {
            typeCount[type] = 1;
        }
    }

    if(types.Count == 1)
    {
        // 옷 종류가 하나뿐인 경우
        answer = typeCount[types.First()];
    }
    else
    {
        // 옷 종류가 여러개일 경우 조합식 계산 - 아무것도 안입은 경우(1개)
        var type = types.ToArray();
        foreach (var t in type)
        {
            // 2가지인 경우 => 0, 1, 2 개중 하나를 선택한다고 했을때 +1을 해준다.
            answer *= (typeCount[t] + 1);
        }

        answer--;
    }
    
    return answer;
}