电话号码的字母组合

电话号码的字母组合

​ 给定一个仅包含数字 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]
	}
}
相关推荐
铅笔小新z6 分钟前
【数据结构】顺序表和链表
数据结构·链表
不会就选b32 分钟前
数据结构之栈的算法题(OJ)
linux·数据结构·算法
漂流瓶jz1 小时前
UVA-1609 不公平竞赛 题解答案代码 算法竞赛入门经典第二版
数据结构·算法·链表·贪心·aoapc·算法竞赛入门经典·uva
hzxpaipai2 小时前
制造业官网产品信息架构怎么设计?从产品分类到后台数据结构
大数据·数据结构
专注API从业者2 小时前
Open‑Claw 实战|无需逆向,快速搭建电商商品监控与数据分析系统
开发语言·数据结构·数据库·数据分析·php
纪念 2292 小时前
数据结构排序(四)
开发语言·数据结构
SelectDB技术团队4 小时前
统一全文检索与 SQL 分析:Apache Doris 日志分析实践
大数据·数据结构·后端·python·全文检索·doris·日志分析
凉茶钱4 小时前
【数据结构】计数排序
数据结构·算法·排序算法
dtq04246 小时前
数据结构 - 线性表 - 双向链表
c语言·数据结构·学习
晊晌_h13 小时前
嵌入式从0到精通——数据结构总结[特殊字符]
数据结构·算法·排序算法