# [LeetCode] 17. Letter Combinations of a Phone Number（手机的 T9 输入法）

• Difficulty: Medium

• Related Topics: String, Backtracking

## Description

Given a string containing digits from `2-9` inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

## Examples

### Example 1

``````Input: digits = "23"
``````

### Example 2

``````Input: digits = ""
Output: []
``````

### Example 3

``````Input: digits = "2"
Output: ["a","b","c"]
``````

## Constraints

• `0 <= digits.length <= 4`
• `digits[i]` is a digit in the range `[‘2‘, ‘9‘]`.

## Solution

``````class Solution {
private val digitToLetter = mapOf(
‘2‘ to "abc",
‘3‘ to "def",
‘4‘ to "ghi",
‘5‘ to "jkl",
‘6‘ to "mno",
‘7‘ to "pqrs",
‘8‘ to "tuv",
‘9‘ to "wxyz"
)

fun letterCombinations(digits: String): List<String> {
if (digits.isBlank()) {
return emptyList()
}
val result = arrayListOf<String>()
backtrack(digits, 0, "", result)
return result
}

private fun backtrack(digits: String, curIndex: Int, curWord: String, result: MutableList<String>) {
if (curWord.length == digits.length) {
return
}
for (letter in digitToLetter[digits[curIndex]]?:"") {
backtrack(digits, curIndex + 1, curWord + letter, result)
}
}
}
``````

[LeetCode] 17. Letter Combinations of a Phone Number（手机的 T9 输入法）

(0)
(0)