给定一个仅包含数字 2-9
的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:"23" 输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
转自:https://blog.csdn.net/xushiyu1996818/article/details/84334799
class Solution { HashMap<Character,char[]> map = new HashMap<>(); List<String> result = new ArrayList<>(); public List<String> letterCombinations(String digits) { int length = digits.length(); if(length == 0){ return result; } map.put('2',new char[]{'a','b','c'}); map.put('3', new char[]{'d','e','f'}); map.put('4', new char[]{'g','h','i'}); map.put('5', new char[]{'j','k','l'}); map.put('6', new char[]{'m','n','o'}); map.put('7', new char[]{'p','q','r','s'}); map.put('8', new char[]{'t','u','v'}); map.put('9', new char[]{'w','x','y','z'}); combine("",digits); return result; } public void combine(String nowStr,String remain){ int length = remain.length(); if(length == 0){ result.add(nowStr); return; } Character now = remain.charAt(0); for(char nowChar:map.get(now)){ combine(nowStr+nowChar,remain.substring(1)); } } }
2019-04-15 22:48:47
23 => ["ad","bd","cd","ae","be","ce","af","bf","cf"]
234=> ["adg","bdg","cdg","aeg","beg","ceg","afg","bfg","cfg","adh"。。。。。。]
1 class Solution: 2 def letterCombinations(self, digits): 3 self.dict = {"2":"abc", "3":"def", "4":"ghi", "5":"jkl", "6":"mno", "7":"pqrs","8":"tuv","9":"wxyz"} 4 if digits == "": 5 return [] 6 result = [""] 7 for digit in digits: 8 strs = self.dict[digit] 9 curResult = [] 10 for char in strs: 11 for res in result: 12 curResult.append(res+char) 13 result = curResult 14 return result
2019-11-28 14:13:09