Skip to content

Instantly share code, notes, and snippets.

@hemant3370
Created October 7, 2020 12:28
Show Gist options
  • Save hemant3370/fbc3745c9cd77135eadcffbd8e3ad0a1 to your computer and use it in GitHub Desktop.
Save hemant3370/fbc3745c9cd77135eadcffbd8e3ad0a1 to your computer and use it in GitHub Desktop.
class Solution {
func letterCombinations(_ digits: String) -> [String] {
let phone: [String: String] = ["2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"]
var output: [String] = []
func backTrack(combination: String, next_digits: String) {
if next_digits.count == 0 {
output.append(combination)
} else {
let digit = String(next_digits[next_digits.startIndex..<next_digits.index(next_digits.startIndex, offsetBy: 1)])
let letters: String = phone[digit] ?? ""
for i in 0..<letters.count {
let start = letters.index(letters.startIndex, offsetBy: i)
let end = letters.index(letters.startIndex, offsetBy: i+1)
let letter = String(letters[start..<end])
backTrack(combination: combination + letter, next_digits: String(next_digits[next_digits.index(next_digits.startIndex, offsetBy: 1)...]))
}
}
}
if digits.count != 0 {
backTrack(combination: "", next_digits: digits)
}
return output
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment