阿里百億補貼:純色 + 自動 + 升級晴雨傘 24.9 元(淘寶自營)
阿新 • • 發佈:2021-05-22
給定一個僅包含數字2-9的字串,返回所有它能表示的字母組合。答案可以按 任意順序 返回。
給出數字到字母的對映如下(與電話按鍵相同)。注意 1 不對應任何字母。
示例 1:
輸入:digits = "23"
輸出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
示例 2:
輸入:digits = ""
輸出:[]
解法一:回溯法
遍歷所有可能的結果,返回成功的結果
List<String> res = new ArrayList<>(); HashMap<Character, String> hash = newHashMap<>(); public List<String> letterCombinations(String digits) { if (digits.length() == 0) return new ArrayList<>(); createHash(); letter(digits, 0, new StringBuilder()); return res; } void letter(String digits, int level, StringBuilder tempres) {if (level == digits.length()) { res.add(tempres.toString()); return; } String str = hash.get(digits.charAt(level)); for (int i = 0; i < str.length(); i++) { tempres.append(str.charAt(i)); letter(digits, level + 1, tempres); tempres.deleteCharAt(tempres.length()- 1); } } void createHash() { hash.put('2', "abc"); hash.put('3', "def"); hash.put('4', "ghi"); hash.put('5', "jkl"); hash.put('6', "mno"); hash.put('7', "pqrs"); hash.put('8', "tuv"); hash.put('9', "wxyz"); }
時間複雜度:O(3m×4n)
空間複雜度:O(m+n)
解法二:佇列
HashMap<Character, String> hash = new HashMap<>(); public List<String> letterCombinations(String digits) { if(digits.length()==0) return new ArrayList<>(); createHash(); Deque<String> queue = new LinkedList<>(); queue.add(""); for (int i = 0; i < digits.length(); i++) { int size = queue.size(); for (int j = 0; j < size; j++) { String nowdigit = hash.get(digits.charAt(i)); String curqueue = queue.poll(); for (int k = 0; k < nowdigit.length(); k++) queue.add(curqueue + nowdigit.charAt(k)); } } List<String> res = new ArrayList<>(); int len = queue.size(); for (int i = 0; i < len; i++) res.add(queue.poll()); return res; } void createHash() { hash.put('2', "abc"); hash.put('3', "def"); hash.put('4', "ghi"); hash.put('5', "jkl"); hash.put('6', "mno"); hash.put('7', "pqrs"); hash.put('8', "tuv"); hash.put('9', "wxyz"); }
總結:心裡要有層次遍歷的樹的結構