题目:
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
![]()
示例:
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
说明:
尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。
看到这个题,我们来分析一下:
1.给定的数字字符串中,每个元素也就是数字有自己对应的字母组合是固定的,因此,可以用Map,
2.返回的队列中就是数字对应的字符的排列组合,因此,可以用嵌套循环。
代码如下:
class Solution {
public List<String> letterCombinations(String digits) {
if(digits == null){
return null;
}
if(digits.length() == 0){
return null;
}
Map<Character,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");
char[] chars = digits.toCharArray();
List<String> res = new ArrayList<>();
res.add("");
for(char ch : chars){
List<String> list = new ArrayList<>();
String str = map.get(ch);
for(String re : res){
for(Character tmp : str.toCharArray()){
String cc = re + tmp;
list.add(cc);
}
}
res = list;
}
return res;
}
}
但是,在我去找资料时,发现了更好的答案,也就是大牛的解法,用回溯法来解决:
代码如下:
public List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<>();
String oneRes = "";
if (digits.equals("")) {
return res;
}
String[] dict = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
int[] digiInt = new int[digits.length()];
for (int i = 0; i < digits.length(); i++) {
digiInt[i] = digits.charAt(i) - ‘0‘;
}
combi(digiInt, 0, dict, res, oneRes);
return res;
}
public void combi(int[] digits, int n, String[] dict, List<String> res, String oneRes) {
if (n == digits.length) {
res.add(oneRes);
return;
}
for (int j = 0; j < dict[digits[n]].length(); j++) {
oneRes = oneRes + dict[digits[n]].charAt(j);
combi(digits, n + 1, dict, res, oneRes);
oneRes = oneRes.substring(0, oneRes.length() - 1);
}
}
原文:https://www.cnblogs.com/youdiaodaxue16/p/10755922.html