프로그래밍/코딩테스트

[LeetCode] 17. Letter Combinations of a Phone Number / Swift

turu 2021. 7. 6. 15:24

[문제 보기]

더보기

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

 

Example 1:

Input: digits = "23" Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]

Example 2:

Input: digits = "" Output: []

Example 3:

Input: digits = "2" Output: ["a","b","c"]

 

Constraints:

  • 0 <= digits.length <= 4
  • digits[i] is a digit in the range ['2', '9'].

 

https://leetcode.com/problems/letter-combinations-of-a-phone-number/

 

Letter Combinations of a Phone Number - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 


n개의 집합들에서 각각 1개씩 뽑는 모든 조합의 경우의 수를 구하는 문제였다.

이 부분은 전에도 한번 고민하고 정리해본 거라서 생각보다 쉽게 구현할 수 있었다.

 

해당 내용 정리한 글:

https://turume.tistory.com/entry/Swift-n%EA%B0%9C-%EC%A7%91%ED%95%A9%EC%97%90%EC%84%9C-%ED%95%98%EB%82%98%EC%94%A9-%EC%9B%90%EC%86%8C-%EB%BD%91%EB%8A%94-%EA%B2%BD%EC%9A%B0%EC%9D%98-%EC%88%98-%EA%B5%AC%ED%95%98%EA%B8%B0

 

[Swift] n개 집합에서 하나씩 원소 뽑는 경우의 수 구하기

https://programmers.co.kr/learn/courses/30/lessons/67258 코딩테스트 연습 - 보석 쇼핑 ["DIA", "RUBY", "RUBY", "DIA", "DIA", "EMERALD", "SAPPHIRE", "DIA"] [3, 7] programmers.co.kr 이 문제풀면서 필요하..

turume.tistory.com

 

제출 코드:

class Solution {
    func letterCombinations(_ digits: String) -> [String] {
        let input = digits.map{Int(String($0))!}
        let container = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
        
        var candidates = [[String]]()
        for element in input {
            candidates.append(container[element - 2].map{String($0)})
        }
        
        if candidates.count < 1 { return [] }
        
        var ans = [String]()
        var index = [Int](repeating: 0, count: candidates.count)
        while index[0] < candidates[0].count {
            var str = ""
            for (i, element) in index.enumerated() {
                str.append(candidates[i][element])
            }
            ans.append(str)
            
            var cur = index.count - 1
            index[cur] += 1
            while cur > 0 {
                if index[cur] >= candidates[cur].count {
                    index[cur] = 0
                    index[cur - 1] += 1
                    cur -= 1
                } else {
                    break
                }
            }
        }
        
        return ans
    }
}
반응형