Skip to content

Instantly share code, notes, and snippets.

@vrat28
Created April 8, 2021 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vrat28/e29a50058d2cd7af543e7729d5587235 to your computer and use it in GitHub Desktop.
Save vrat28/e29a50058d2cd7af543e7729d5587235 to your computer and use it in GitHub Desktop.
Letter Combinations of a phone number - Leetcode #17
class Solution {
let map:[Character:String] = ["2" : "abc", "3": "def", "4" : "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv","9":"wxyz"]
func letterCombinations(_ digits: String) -> [String] {
guard digits.isEmpty == false else { return [] }
var output = [String]()
combinations_dfs_helper(digits,"",0,&output)
return output
}
func combinations_dfs_helper(_ digits:String,_ current:String,_ index:Int,_ output: inout [String]){
if index == digits.count {
output.append(current)
return
}
let charIndex = digits.index(digits.startIndex, offsetBy:index)
let currentChar = digits[charIndex]
let charDigits = Array(map[currentChar]!)
for i in 0..<charDigits.count {
let newChar = current + "\(charDigits[i])"
combinations_dfs_helper(digits, newChar, index + 1, &output)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment