Question:java
給定一個僅包含數字 2-9
的字符串,返回全部它能表示的字母組合。git
給出數字到字母的映射以下(與電話按鍵相同)。注意 1 不對應任何字母。code
示例:字符串
輸入:"23" 輸出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
說明:
儘管上面的答案是按字典序排列的,可是你能夠任意選擇答案輸出的順序。get
Answer:it
class Solution { public List<String> letterCombinations(String digits) { List<String> tmp = new ArrayList<>(); List<String> result = new ArrayList<>(); Map map = new HashMap(); map.put('2', "abc"); map.put('3', "def"); map.put('4', "ghi"); map.put('5', "jkl"); map.put('6', "mno"); map.put('7', "pqrs"); map.put('8', "tuv"); map.put('9', "wxyz"); if (digits != null && digits.length() > 0) { char[] numbers = digits.toCharArray(); for (char c : map.get(numbers[0]).toString().toCharArray()) { result.add(String.valueOf(c)); } for (int i = 1; i < numbers.length; i++) { tmp.clear(); tmp.addAll(result); result.clear(); String shouldAdd = map.get(numbers[i]).toString(); for (String s : tmp) { for (char c1 : shouldAdd.toCharArray()) { result.add(s + String.valueOf(c1)); } } } } return result; } }
此用例運行花時5ms;順手貼一下運行耗時1ms大佬的解法;io
class Solution { String[] codes = new String[]{"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; public List<String> letterCombinations(String digits) { if(digits == null || digits.equals("")){ return new ArrayList<>(); } List<String> result = new ArrayList<>(); backtrace(digits, result, "", 1, digits.length()); return result; } private void backtrace(String digits, List<String> list, String str, int deep, int n){ if(deep == n){ for(char c : codes[digits.charAt(deep-1) - '0' -2].toCharArray()){ list.add(str+c); } }else{ for(char c : codes[digits.charAt(deep-1) - '0' -2].toCharArray()){ backtrace(digits, list, str+c, deep+1, n); } } } }