LeetCode-17-The alphabet of the phone number
Problem description: Given a string containing only the numbers 2-9, return all the letter combinations it can represent. Answers can be returned in any order.
The mapping of numbers to letters is given below (same as phone keys). Note that 1 does not correspond to any letters.
Question link: LeetCode-17-The letter combination of the phone number
Problem-solving ideas:
- You need to write the mapping relationship between numbers and letters yourself
- It is an ordinary backtracking algorithm, just follow the three steps of backtracking
What's very strange is that if I write res and sb as all variables, then the results of the previous sample will appear in the results of the later sample when I submit it. I have no choice but to change it.
Code:
class Solution {
/**
* 1.将数字映射为对应的字母
* 2.开始组合
* 树的深度由输入字符串的长度控制
* 树的宽度由digits[0]的长度控制
*/
List<String> res = new ArrayList<>();// 结果集
StringBuilder sb = new StringBuilder();// 相当于path,收获单个结果
public List<String> letterCombinations(String digits) {
if (digits.length()==0 || digits== null){
return res;
}
// 自己需要将数字映射为对应的字母
String[] numString = new String[]{
"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
int k = digits.length();// 树的深度
backTracking(numString, k, digits, 0);
return res;
}
/**
* @param numString 字母和数字的映射
* @param k 树的深度,也就是digits.length()
* @param index 表示遍历到哪个数字
* @param digits
*/
private void backTracking(String[] numString, int k, String digits,int index){
if (sb.length() == k){
res.add(sb.toString());
return;
}
String singleStr = numString[digits.charAt(index)-'0'];// abc
for (int i = 0; i < singleStr.length(); i++) {
// 不需要 startIndex帮忙做去重的操作
sb.append(singleStr.charAt(i));
backTracking(numString, k, digits, index+1);
sb.deleteCharAt(sb.length()-1);// 弹出去
}
}
} * @param numString 字母和数字的映射
* @param k 树的深度,也就是digits.length()
* @param index 表示遍历到哪个数字
* @param digits
*/
private static void backTracking(String[] numString, int k, String digits,List<String> res, StringBuilder sb, int index){
if (sb.length() == k){
System.out.println(sb.toString());
res.add(sb.toString());
return;
}
String singleStr = numString[digits.charAt(index)-'0'];// abc
for (int i = 0; i < singleStr.length(); i++) {
// 不需要 startIndex帮忙做去重的操作
backTracking(numString, k, digits, res, sb.append(singleStr.charAt(i)), index+1);
sb.deleteCharAt(sb.length()-1);
}
}
}