Leetcode [17]. A telephone number, a letter (Letter Combinations of a Phone Number)
Subject description:
Given numbers only a 2-9
string, it returns all letter combinations indicated.
Given digital map to letters as follows (the same telephone key). Note 1 does not correspond to any alphabet.
Example:
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
analysis:
Title requirements of a given length comprising 2-9 N number of strings, each number corresponding to the letters, all required combinations of these letters, as shown in FIG.
We can use the Map that stores digital key 2-9, with the digital value stored in the corresponding letter (e.g., corresponding to 2 abc).
Recursion can solve this problem, the first index string entered = 0, according to the value argument (e.g. key = 2, value = "abc") corresponding to the key on the Map, the letters were taken, and into the next process.
Map storage process with the following:
Map<String, String> map = 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"); }};
You can see, the answer requires a List <String> as a return, then we can:
List<String> ans = new ArrayList<>();
Next to the write function, we create a function called the dfs:
public void dfs(String digits, int step, String answer) { if (step == digits.length()) { ans.add(answer); return; } char c = digits.charAt(step); String value = map.get(c +""); for (int i = 0; i < value.length(); i++) { dfs(digits, step + 1, answer + value.charAt(i)); } }
All together, and finally AC code:
class Solution { List<String> ans = new ArrayList<>(); Map<String, String> map = 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"); }}; public List<String> letterCombinations(String digits) { if (digits.length() == 0 || digits == null) return ans; dfs(digits, 0, ""); return ans; } public void dfs(String digits, int step, String answer) { if (step == digits.length()) { ans.add(answer); return; } char c = digits.charAt(step); String value = map.get(c + ""); for (int i = 0; i < value.length(); i++) { dfs(digits, step + 1, answer + value.charAt(i)); } } }