电话号码的字母组合

电话号码的字母组合

​ 给定一个仅包含数字 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]
	}
}
相关推荐
zhengzhouliuhaha9 分钟前
智能医疗设备控费系统:以全院一体化管控,筑牢医疗资源“安全阀”
大数据·数据结构·人工智能·算法·安全·机器学习·软件需求
Yiyaoshujuku2 小时前
化合物数据集API接口(数据结构及样例)
java·网络·数据结构
fu的博客2 小时前
【数据结构16】图:基于邻接矩阵、邻接表实现DFS/BFS
数据结构·算法
言存3 小时前
力扣热题283 移动零
数据结构·算法·leetcode
Lewiis3 小时前
白话桶排序
数据结构·算法·golang·排序算法
iiiiyu4 小时前
IO流相关编程题
java·大数据·开发语言·数据结构·数据库·mysql
Darling噜啦啦5 小时前
JS 数据结构实战:从栈队列到链表,一文吃透数组底层原理与线性数据结构
前端·javascript·数据结构
洛水水5 小时前
【力扣100题】80.寻找旋转排序数组中的最小值
数据结构·算法·leetcode
legend050709ComeON6 小时前
常见面试题-leetcode
数据结构·算法·leetcode
Lsk_Smion6 小时前
力扣实训 _ [207].课程表/图论
数据结构·leetcode·图论