题目:
Letter Combinations of a Phone Number
Given a string containing digits from
2-9
inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].说明:
尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。
解题分析:
可以采用:回溯法;
由于要求所有的可能性,因此考虑使用回溯法进行求解。回溯是一种通过穷举所有可能情况来找到所有解的算法。如果一个候选解最后被发现并不是可行解,回溯算法会舍弃它,并在前面的一些步骤做出一些修改,并重新尝试找到可行解。究其本质,其实就是枚举。
如果没有更多的数字需要被输入,说明当前的组合已经产生。
如果还有数字需要被输入:
遍历下一个数字所对应的所有映射的字母
将当前的字母添加到组合最后;
时间复杂度:O(2^n)
class Solution{
private String letterMap[] = {
"", //0
"", //1
"abc", //2
"def", //3
"ghi", //4
"jkl", //5
"mno", //6
"pqrs", //7
"tuv", //8
"wxyz" //9
};
private ArrayList<String> result;
public List<String> letterCombinations(String digits){
result = new ArrayList<String>();
// 如果为空串,直接返回
if(digits.length() == 0){
return result;
}
dfs(digits, 0, "");
return result;
}
public void dfs(String digits, int index, String s){
// 数字取完了,就开始添加组合字母
if(index == digits.length()){
result.add(s);
return;
}
// 获取当前数字
Character c = digits.charAt(index);
// 获取数字对应的字母映射
String letters = letterMap[c - '0'];
// 对获取到的字母映射进行遍历,与其他字母映射进行组合
for(int i = 0; i < letters.length(); i ++){
dfs(digits, index + 1, s + letters.charAt(i));
}
}
}