LeetCode 17. 电话号码的字母组合

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

🌈🌈😄😄

欢迎来到茶色岛独家岛屿本期将为大家揭晓LeetCode 17. 电话号码的字母组合做好准备了么那么开始吧。

🌲🌲🐴🐴

一、题目名称

17. 电话号码的字母组合

二、题目要求

给定一个仅包含数字 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'] 的一个数字。

五、解决办法

回溯

使用哈希表存储每个数字对应的所有可能的字母然后进行回溯操作。

回溯过程中维护一个字符串表示已有的字母排列如果未遍历完电话号码的所有数字则已有的字母排列是不完整的。该字符串初始为空。每次取电话号码的一位数字从哈希表中获得该数字对应的所有可能的字母并将其中的一个字母插入到已有的字母排列后面然后继续处理电话号码的后一位数字直到处理完电话号码中的所有数字即得到一个完整的字母排列。然后进行回退操作遍历其余的字母排列。

六、代码实现

class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> combinations = new ArrayList<String>();
        if (digits.length() == 0) {
            return combinations;
        }
        Map<Character, String> phoneMap = new HashMap<Character, String>() {{
            put('2', "abc");
            put('3', "def");
            put('4', "ghi");
            put('5', "jkl");
            put('6', "mno");
            put('7', "pqrs");
            put('8', "tuv");
            put('9', "wxyz");
        }};
        backtrack(combinations, phoneMap, digits, 0, new StringBuffer());
        return combinations;
    }

    public void backtrack(List<String> combinations, Map<Character, String> phoneMap, String digits, int index, StringBuffer combination) {
        if (index == digits.length()) {
            combinations.add(combination.toString());
        } else {
            char digit = digits.charAt(index);
            String letters = phoneMap.get(digit);
            int lettersCount = letters.length();
            for (int i = 0; i < lettersCount; i++) {
                combination.append(letters.charAt(i));
                backtrack(combinations, phoneMap, digits, index + 1, combination);
                combination.deleteCharAt(index);
            }
        }
    }
}

注意事项

  • 删除字符串中某个位置的字符可以使用StringBuffer类的deleteCharAt()方法它接受一个整数参数表示要删除的字符的位置。这里的参数是index表示当前字母在组合中的位置如此可以确保删除正确的字母。
  • 返回值是 List<String> 类型,则使用 Collections.emptyList() 方法返回一个空字符串列表。
  • 另外在Java中使用Collections.emptyList() 方法返回一个空集合emptySet() 返回空setemptyMap() 返回空map。

 

 

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6