17. 电话号码的字母组合
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
说明:
尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。
回溯法
时间:3m*4n(m:除79之外的数字的个数, n:7或9的个数),不同的字母组合一共有 3m*4n种,需要遍历每一种字母组合
空间:m+n
class Solution {
public List<String> letterCombinations(String digits) {
List<String> list = new ArrayList<>();
//特例
if(digits == null || digits.length() == 0)
return list;
//数字到字母的映射
Map<Character, char[]> map = new HashMap<>();
map.put('2', new char[]{'a', 'b', 'c'});
map.put('3', new char[]{'d', 'e', 'f'});
map.put('4', new char[]{'g', 'h', 'i'});
map.put('5', new char[]{'j', 'k', 'l'});
map.put('6', new char[]{'m', 'n', 'o'});
map.put('7', new char[]{'p', 'q', 'r', 's'});
map.put('8', new char[]{'t', 'u', 'v'});
map.put('9', new char[]{'w', 'x', 'y', 'z'});
StringBuffer sb = new StringBuffer();
dfs(list, digits, map, sb, 0);
return list;
}
private void dfs(List<String> list, String digits, Map<Character, char[]> map, StringBuffer sb, int begin)
{
if(digits.length() == sb.length())
{
list.add(sb.toString());
return;
}
char[] ch = map.get(digits.charAt(begin));
for(int j = 0; j < ch.length; j++)
{
sb.append(ch[j]);
dfs(list, digits, map, sb, begin + 1);
sb.deleteCharAt(sb.length() - 1);
}
}
}
或使用数组实现
class Solution {
public List<String> letterCombinations(String digits) {
List<String> list = new ArrayList<>();
//特例
if(digits == null || digits.length() == 0)
return list;
//数字到字母的映射
String[] str = new String[10];
str[2] = "abc";
str[3] = "def";
str[4] = "ghi";
str[5] = "jkl";
str[6] = "mno";
str[7] = "pqrs";
str[8] = "tuv";
str[9] = "wxyz";
StringBuffer sb = new StringBuffer();
dfs(list, digits, str, sb, 0);
return list;
}
private void dfs(List<String> list, String digits, String[] str, StringBuffer sb, int begin)
{
if(digits.length() == sb.length())
{
list.add(sb.toString());
return;
}
char[] ch = str[digits.charAt(begin) - '0'].toCharArray();
for(int j = 0; j < ch.length; j++)
{
sb.append(ch[j]);
dfs(list, digits, str, sb, begin + 1);
sb.deleteCharAt(sb.length() - 1);
}
}
}
如上