LeetCode-Letter-Combinations-Of-A-Phone-Number
阿新 • • 發佈:2018-12-16
一、Description
給定一個字串,包含從2 - 9位數,返回所有可能代表的字母組合。一個數字對映的字母的可能(就像在電話裡按鈕)如下所示。請注意,1不對映到任何字母。
Example:
Input: "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
二、Analyzation
這道題可以用深搜來解決。先通過map建立2-9對所有字母的一個對映,對於每一次遞迴,將當前字串指向的下標和list傳過去,如果下標等於字串的長度,遞迴結束,否則就通過一個全域性的temp進行疊加字母,直到結束。
三、Accepted code
class Solution { String temp = ""; public List<String> letterCombinations(String digits) { List<String> list = new ArrayList<>(); if (digits == null || digits.length() == 0) { return list; } Map<Integer, String> 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"); dfs(map, list, 0, digits); return list; } public void dfs(Map<Integer, String> map, List<String> list, int index, String digits) { if (index == digits.length()) { list.add(temp); return ; } for (int i = 0; i < map.get(digits.charAt(index) - '0').length(); i++) { char tmp = map.get(digits.charAt(index) - '0').charAt(i); temp += tmp + ""; dfs(map, list, index + 1, digits); temp = temp.substring(0, temp.length() - 1); } } }