思路:
本题可以使用回溯法进行解决
在leetcode的官网题解的评论之下,有人质疑该方法只不过是递归构造,暴力枚举,并没有所谓的回溯,实际上大可不必纠结这样的细节
因为所谓的回溯法本质上还是属于暴力法的,只不过它将生成过程和检查过程结合了起来,不必对 解空间树 的叶结点一一地进行检查了,相当于对解空间树做了一次剪枝,把错误结果的分支去掉;
而如果画出此题的解空间树,会发现压根也不需要剪枝,:
但是如果非要说回溯的话,将递归边界看作是一次回溯,将当前字符串长度为零,看作是错误的结果,也未尝不可。
官方题解:
class Solution {
Map<String, String> phone = new HashMap<String, String>() {{
put("2", "abc");
put("3", "def");
put("4", "ghi");
put("5", "jkl");
put("6", "mno");
put("7", "pqrs");
put("8", "tuv");
put("9", "wxyz");
}};
List<String> output = new ArrayList<String>();
public void backtrack(String combination, String next_digits) {
// if there is no more digits to check
if (next_digits.length() == 0) {
// the combination is done
output.add(combination);
}
// if there are still digits to check
else {
// iterate over all letters which map
// the next available digit
String digit = next_digits.substring(0, 1);
String letters = phone.get(digit);
for (int i = 0; i < letters.length(); i++) {
String letter = phone.get(digit).substring(i, i + 1);
// append the current letter to the combination
// and proceed to the next digits
backtrack(combination + letter, next_digits.substring(1));
}
}
}
public List<String> letterCombinations(String digits) {
if (digits.length() != 0)
backtrack("", digits);
return output;
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/solution/dian-hua-hao-ma-de-zi-mu-zu-he-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。