电话号码的字母组合

电话号码的字母组合

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

题解

经典的回溯的思想,没什么特别的地方

java 复制代码
class Solution {
    List<String> ans = new ArrayList<String>();
    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");
        }
    };

    public List<String> letterCombinations(String digits) {
        if(digits.length() == 0){
            return ans;
        }
        StringBuffer str = new StringBuffer();
        letterCombinations(digits, 0, str);
        return ans;
    }

    private void letterCombinations(String digits, int index, StringBuffer str) {
        if (index == digits.length()) {
            ans.add(str.toString());
            return;
        }
        String phone = phoneMap.get(digits.charAt(index));
        for (int i = 0; i < phone.length(); i++) {
            str.append(phone.charAt(i));
            letterCombinations(digits, index + 1, str);
            str.deleteCharAt(str.length() - 1);
        }
    }
}
go 复制代码
var phoneMap = map[byte]string{
	'2': "abc",
	'3': "def",
	'4': "ghi",
	'5': "jkl",
	'6': "mno",
	'7': "pqrs",
	'8': "tuv",
	'9': "wxyz",
}

func letterCombinations(digits string) []string {
    var ans []string = []string{}
	if len(digits) == 0 {
		return ans
	}
	letterCombinationsHelper(digits, 0, "", &ans)
	return ans
}

func letterCombinationsHelper(digits string, index int, str string, ans *[]string) {
	if index == len(digits) {
		*ans = append(*ans, str)
		return
	}
	phone := phoneMap[digits[index]]
	for i := 0; i < len(phone); i++ {
		str += string(phone[i])
		letterCombinationsHelper(digits, index+1, str, ans)
		str = str[:len(str)-1]
	}
}
相关推荐
tobias.b25 分钟前
408真题-2009-7-数据结构-无向连通图性质
数据结构·算法·408考研·408真题·真题解析
阿猿收手吧!1 小时前
【C++】JSON核心数据结构解析及JSONCPP使用
数据结构·c++·json
tobias.b1 小时前
408真题解析-2009-9-数据结构-小根堆-排序
数据结构·408考研·408真题·真题解析
D_FW2 小时前
数据结构第二章:线性表
数据结构·算法
tobias.b2 小时前
408真题解析-2009-8-数据结构-B树-定义及性质
数据结构·b树·计算机考研·408考研·408真题
hk11242 小时前
【Architecture/Refactoring】2026年度企业级遗留系统重构与高并发架构基准索引 (Grandmaster Edition)
数据结构·微服务·系统架构·数据集·devops
im_AMBER3 小时前
Leetcode 95 分割链表
数据结构·c++·笔记·学习·算法·leetcode·链表
无限进步_3 小时前
【C语言】堆(Heap)的数据结构与实现:从构建到应用
c语言·数据结构·c++·后端·其他·算法·visual studio
再难也得平3 小时前
两数之和和字母异位词分组
数据结构·算法
黎雁·泠崖3 小时前
【线性表系列入门篇】从顺序表到链表:解锁数据结构的进化密码
c语言·数据结构·链表