17. 电话号码的字母组合
17. 电话号码的字母组合
方法一:回溯
class Solution {
public List letterCombinations(String digits) {
if (digits == null || digits.length() == 0) {
return new ArrayList<>();
}
Map 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");
List res = new linkedList<>();
search("", digits, 0, res, map);
return res;
}
private void search(String s, String digits, int i, List res, Map map) {
//terminator
if (i == digits.length()) {
res.add(s);
return;
}
//process
String letters = map.get(digits.charAt(i));
for (int j = 0; j < letters.length(); j++) {
//drill down
search(s + letters.charAt(j), digits, i + 1, res, map);
}
//reverse
// 回溯算法用于寻找所有的可行解,如果发现一个解不可行,
// 则会舍弃不可行的解。
// 在这道题中,由于每个数字对应的每个字母都可能进入字母组合,
// 因此不存在不可行的解,直接穷举所有的解即可。
}
}