题目描述:
给定一个仅包含数字 2-9
的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:"23" 输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
题解:
class Solution { public List<String> letterCombinations(String digits) { Map<String, String> phone = new HashMap<String, 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"); }}; List<String> res = new ArrayList<>(); if (digits.length()==0){ return Collections.EMPTY_LIST; }else{ String resString = ""; back(res,digits,0,resString, phone); } return res; } //回溯函数 public static void back(List<String> res, String digits, int in, String resString,Map<String, String> phone){ if(resString.length() == digits.length()){ res.add(resString); return; }else{ Integer length = phone.get(digits.substring(in,in+1)).length(); for(int index = 0;index< length;index ++){ resString += phone.get(digits.substring(in,in+1)).substring(index,index+1); in++; back(res,digits,in,resString,phone); resString = resString.substring(0,resString.length()-1); in --; } } }}