Advertisement
HXXXXJ

17. Letter Combinations of a Phone Number

Jan 27th, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.19 KB | None | 0 0
  1.  
  2.     let map : [Character : String] = [ "2" : "abc",
  3.                                         "3" : "def",
  4.                                        "4" : "ghi",
  5.                                        "5" : "jkl",
  6.                                        "6" : "mno",
  7.                                        "7" : "pqrs",
  8.                                        "8" : "tuv",
  9.                                        "9" : "wxyz"]
  10.                                        
  11.     func letterCombinations(_ digits: String) -> [String] {
  12.         guard digits.count > 0 else { return [String]()}
  13.         let arr = Array(digits)
  14.         var list = [Character]()
  15.         var res = [String]()
  16.         combinations(arr, 0, &list, &res)
  17.         return res
  18.     }
  19.     func combinations(_ arr:[Character], _ index: Int, _ list: inout [Character], _ res: inout [String]){
  20.         if list.count == arr.count{
  21.             res.append(String(list))
  22.             return
  23.         }
  24.        
  25.         if let currList = map[arr[index]]{
  26.             for char in currList{
  27.                 list.append(char)
  28.                 combinations(arr, index + 1, &list, &res)
  29.                 list.removeLast()
  30.             }
  31.         }
  32.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement