...
본문 바로가기

코딩테스트

LeetCode - 17. Letter Combinations of a Phone Number - swift

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

 

 

 

간단한 조합문제이다. 

2~9까지 각 해당하는 문자들이 존재한다. 

2~9 인덱스를 활용하기위해 미리 문자배열들을 만들어두었다. 

 

각 인덱스를 통해서 재귀함수로 조합을 뽑아낸다. 

 

class Solution {
    
    var list = [[], [], ["a","b","c"], ["d","e","f"], ["g","h","i"],
    ["j","k","l"],["m","n","o"],["p","q","r","s"],["t","u","v"],["w","x","y","z"]]
    
    var answer = [String]()
    var stack = ""
    func letterCombinations(_ digits: String) -> [String] {
        dfs(0, 0, digits.count, digits.map{Int(String($0))!})
        return answer
    }
    
    func dfs(_ count: Int, _ idx: Int, _ mx: Int, _ digits: [Int]  ) {
        if count == mx {
            if stack.isEmpty { return }
            answer.append(stack)
            return
        }
        
        for i in list[digits[idx]] {
            stack.append(i)
            dfs(count+1, idx+1, mx, digits)
            stack.removeLast()
        }
    }
}