Created
April 8, 2021 19:20
-
-
Save vrat28/e29a50058d2cd7af543e7729d5587235 to your computer and use it in GitHub Desktop.
Letter Combinations of a phone number - Leetcode #17
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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