import java.util.*; public class Solution { private ArrayList<String> res = new ArrayList<>(); private Map<Character, String> numMap = new HashMap<>(); /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param num string字符串 * @return string字符串ArrayList */ public ArrayList<String> phoneNumber (String num) { // write code here if (num == null || num.length() < 1) { return res; } numMap.put('2', "abc"); numMap.put('3', "def"); numMap.put('4', "ghi"); numMap.put('5', "jkl"); numMap.put('6', "mno"); numMap.put('7', "pqrs"); numMap.put('8', "tuv"); numMap.put('9', "wxyz"); backtrack(num, 0, new ArrayList<>()); return res; } private void backtrack(String num, int start, List<Character> list) { if (start == num.length() && list.size() == num.length()) { res.add(list2Str(list)); return; } String alpha = numMap.get(num.charAt(start)); for (int i = 0; i < alpha.length(); i++) { list.add(alpha.charAt(i)); backtrack(num, start + 1, list); list.remove(list.size() - 1); } } private String list2Str(List<Character> list) { StringBuilder sb = new StringBuilder(); for (char ch : list) { sb.append(ch); } return sb.toString(); } }