首页 > 其他分享 >leetcode-17. 电话号码的字母组合

leetcode-17. 电话号码的字母组合

时间:2022-12-26 15:32:55浏览次数:39  
标签:digits index combination 17 phoneMap combinations put 字母组合 leetcode

17. 电话号码的字母组合
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。





示例 1:

输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
示例 2:

输入:digits = ""
输出:[]
示例 3:

输入:digits = "2"
输出:["a","b","c"]


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);
}
}
}
}

标签:digits,index,combination,17,phoneMap,combinations,put,字母组合,leetcode
From: https://blog.51cto.com/u_12550160/5969125

相关文章

  • Leetcode207
    numCourses->总的课程数目Prerequisited->pairinalistdenotinghavetofinishbtostudya class Solution:    def canFinish(self, numCourses: int......
  • 【2022-12-17】连岳摘抄
    23:59明智的做法是把你的愤怒指向问题,而不是指向人,把你的精力集中在寻求解决方案上,而不是集中在寻求借口上。                  ......
  • AHOI,但是初中组,2017-2018
    你觉得我这种彩笔像是能去做省选题的样子吗?=w=合肥人,做初中的屑安徽题,很正常吧。AH也不知道为啥搞啥市赛啊区赛啊省赛啊就挺离谱的反正摆烂人也不想打┓( ´∀` )┏20......
  • Java编程思想17
    第二十一章:并发基本的线程机制  并发编程使我们可以将程序划分为多个分离的、独立运行的任务。通过使用多线程机制,这些独立任务(也被称为子任务)中的每一个都将由执行线程......
  • 代码随想录算法训练营Day25|216. 组合总和 III、17. 电话号码的字母组合
    代码随想录算法训练营Day25|216.组合总和III、17.电话号码的字母组合216.组合总和III216.组合总和III与「77.组合」类似,但区别在于题干要求的变化:只使用数字1......
  • [LeetCode] 1759. Count Number of Homogenous Substrings
    Givenastring s,return thenumberof homogenous substringsof s. Sincetheanswermaybetoolarge,returnit modulo 109 +7.Astringis homogenou......
  • Visual Studio 2017(vs2017)绿色便携版-北桃特供
    原版的VisualStudio2017有几十G,安装起来特别慢,不少用户叫苦连天。该版本是精简过的vs2017,且简化了原来的安装程序,特别适用于教学、个人开发者、某些要求不高的企业。该绿......
  • 力扣---217. 存在重复元素
    给你一个整数数组nums。如果任一值在数组中出现至少两次,返回true;如果数组中每个元素互不相同,返回false。示例1:输入:nums=[1,2,3,1]输出:true示例2:输入:nums=[1......
  • P1772 [ZJOI2006] 物流运输
    P1772[ZJOI2006]物流运输题意:需要将物品从\(A\)移动到\(B\),需要\(n\)天才能运输完成,运输过程中需要转停很多个码头。求指定一个\(n\)天的运输计划,使得总成本......
  • 1763. 最长的美好子字符串 暴力枚举
    题目:当一个字符串 s 包含的每一种字母的大写和小写形式 同时 出现在 s 中,就称这个字符串 s 是 美好 字符串。比方说,"abABB" 是美好字符串,因为 'A' 和 'a' ......