版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Apple_hzc/article/details/83210644
一、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);
}
}
}