【陪伴式刷题】Day 22|回溯|17.电话号码的字母组合(Letter Combinations of a Phone Number)

752 阅读2分钟

刷题顺序按照代码随想录建议

题目描述

英文版描述

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 digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

Example 1:

Input: digits = "23" Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]

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'].

英文版地址

leetcode.com/problems/le…

中文版描述

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

示例 1:

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

示例 2:

输入: digits = "" 输出: []

示例 3:

输入: digits = "2" 输出: ["a","b","c"]

提示:

  • 0 <= digits.length <= 4
  • digits[i] 是范围 ['2', '9'] 的一个数字。

中文版地址

leetcode.cn/problems/le…

解题方法

递归法

class Solution {
    List<String> sResult = new LinkedList<>();
    List<String> result = new LinkedList<>();
    Map<Character, String> map = new HashMap<>();

    /**
     * @param digits
     * @return
     */
    public List<String> letterCombinations(String digits) {
        map.put('2', "abc");
        map.put('3', "def");
        map.put('4', "ghi");
        map.put('5', "jkl");
        map.put('6', "mno");
        map.put('7', "pqrs");
        map.put('8', "tuv");
        map.put('9', "wxyz");

        backTracking(0, digits);
        return result;

    }

    private void backTracking(int i, String digits) {
         if (digits == null || digits.isEmpty()) {
            return;
        }
        if (i == digits.length()) {
            String join = String.join("", sResult);
            result.add(join);
            return;
        }
        String s = map.get(digits.charAt(i));
        if (s == null || s.isEmpty()) {
            return;
        }
        for (int j = 0; j < s.length(); j++) {
            sResult.add(s.charAt(j) + "");
            backTracking(i + 1, digits);
            sResult.remove(sResult.size() - 1);
        }

    }
}

复杂度分析

  • 时间复杂度:O(3^m×4^n),其中 m 是输入中对应 3 个字母的数字个数(包括数字 2、3、4、5、6、8),n 是输入中对应 4 个字母的数字个数(包括数字 7、9),m+n 是输入数字的总个数。当输入包含 m 个对应 3 个字母的数字和 n 个对应 4 个字母的数字时,不同的字母组合一共有 3^m×4^n 种,需要遍历每一种字母组合
  • 空间复杂度:O(m+n),其中 m 是输入中对应 3 个字母的数字个数,n 是输入中对应 4 个字母的数字个数,m+n 是输入数字的总个数。除了返回值以外,空间复杂度主要取决于哈希表以及回溯过程中的递归调用层数,哈希表的大小与输入无关,可以看成常数,递归调用层数最大为 m+n