LeetCode17:电话号码的字母组合

原题连接:. - 力扣(LeetCode)

题目描述

给定一个仅包含数字 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(combination.length() - 1);
            }
        }
    }
}

复杂度分析

  • 时间复杂度:O(4^N),其中 N 是输入数字的长度。每个数字最多对应 4 个字母(例如 7 和 9),因此组合的总数为 4^N。
  • 空间复杂度:O(N),主要是递归调用栈的空间和存储组合的空间。组合的空间消耗与结果的大小成正比,但在构建过程中,最大深度为 N。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值