프로그래머스 의상

quokka·2024년 5월 19일
0

코딩테스트

목록 보기
63/63

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

옷의이름과 옷의종류를 인자로 전달받는다. 옷을 하나입었을때부터 옷의 모든 조합이 몇개인지 파악한다.
테스트 1번에서만 시간초과가 나고있는데 시간복잡도가 낮은 코드로의 변환이 필요하다.

import Foundation

func solution(_ clothes:[[String]]) -> Int {
    var dictionary = [String: Int]()
    var resultCount = 0
    for cloth in clothes {
        if let count = dictionary[cloth[1]] {
            dictionary.updateValue(count+1, forKey: cloth[1])
        } else {
            dictionary.updateValue(1, forKey: cloth[1])
        }
    }
    
    for i in 1...dictionary.keys.count {
        let combinationArray = combi(Array(dictionary.keys), i)
        for combination in combinationArray {
            var count = 1
            for cloth in combination {
                if let clothCount = dictionary[cloth] {
                    count *= clothCount
                }
            }
            resultCount += count
        }
    }
    return resultCount
}

func combi<T>(_ array: [T], _ targetNum: Int) -> [[T]] {
    var result = [[T]]()

    func combination(_ index: Int, _ nowCombi: [T]) {
        if nowCombi.count == targetNum {
            result.append(nowCombi)
            return
        }
        for i in index..<array.count {
            combination(i + 1, nowCombi + [array[i]])
        }
    }
    combination(0, [])
    return result
}
profile
iOS를 공부하는 개발자입니다~ㅎㅎ

0개의 댓글

관련 채용 정보