Swift solution - Backtracking


  • 0
    class Solution {
        private let keys = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
        
        func letterCombinations(_ digits: String) -> [String] {
            if digits.characters.count == 0 {
                return []
            }
            
            var result = [String]()
            let characters = Array(digits.characters)
            
            backtracking("", characters, 0, &result)
            
            return result
        }
        
        private func backtracking(_ candidate: String, _ characters: [Character], _ pos: Int, _ result: inout [String]) {
            if pos >= characters.count {
                result.append(candidate)
                return
            }
            
            let digit = String(characters[pos])
            let key = keys[digit.asciiValueOfCharacter - "0".asciiValueOfCharacter]
            let letters = Array(key.characters)
            for i in 0..<letters.count {
                backtracking(candidate + String(letters[i]), characters, pos + 1, &result)
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.