Use kotlin to solve the problem of letter combinations of phone numbers with backtracking

17. Alphabet combinations for phone numbers

Moderate difficulty

2474

Given a  2-9 string containing only numbers, return all possible combinations of letters it can represent. Answers can be returned in  any order  .

The mapping of numbers to letters is given as follows (same as for phone keys). Note that 1 does not correspond to any letter.

Example 1:

输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]

Example 2:

Input: digits = ""
 Output: []

Example 3:

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

hint:

  • 0 <= digits.length <= 4
  • digits[i] is  ['2', '9'] a number in the range.

Passes 696,168 Commits 1,198,761

 answer:

We first define an alphabet that maps numbers to corresponding letter combinations. Next, a result set is defined result. In the function letterCombinations, we first judge the special case, if the number string is empty, then return an empty list. Otherwise, we start recursively calling the traceback function backtrack.

In the backtracking function, we first judge whether the end of the number string has been reached, and if so, add the current combined string to the result set. Otherwise, we take the combination of letters corresponding to the current number, and for each letter, add it to the combined string, call the function recursively, and finally backtrackremove the letter from the combined string (backtracking to the previous step).

In this way, when the backtracking function returns, we can get all the letter combinations.

class Solution {
     private val letterMap = arrayOf("", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz")
    private val result = mutableListOf<String>()
    fun letterCombinations(digits: String): List<String> {
        if (digits.isEmpty()) {
            return emptyList()
        }
        backtrack(digits, 0, StringBuilder())
        return result
    }
    private fun backtrack(digits: String, index: Int, combination: StringBuilder) {
        if (index == digits.length) {
            result.add(combination.toString())
            return
        }
        val digit = digits[index].toString().toInt()
        val letters = letterMap[digit]
        for (i in letters.indices) {
            combination.append(letters[i])
            backtrack(digits, index + 1, combination)
            combination.deleteCharAt(combination.length - 1)
        }
    }
}

The backtracking method is a violent solution. Interestingly, it has achieved no repetitions and no omissions. Although it is exhaustive, it collects all the results that meet the situation. If all the backtracking methods are mastered, then the game of Sudoku becomes meaningless.

Guess you like

Origin blog.csdn.net/weixin_41579872/article/details/130911232