🌕 17. 电话号码的字母组合
2022年6月9日
- algorithm
🌕 17. 电话号码的字母组合
难度: 🌕
问题描述
解法
class Solution {
List<String> res = new ArrayList<>();
String[] array = new String[] {"#", "#", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public List<String> letterCombinations(String digits) {
// 思路:
// 将电话号码信息存入数组
// 回溯
int len = digits.length();
// 特殊情况特判
if(len == 0) {
return res;
}
LinkedList<Character> path = new LinkedList<>();
mySol(digits, len, 0, path);
return res;
}
private void mySol(String digits, int len, int index, LinkedList<Character> path) {
// 递归终止条件
if(index == len) {
res.add(getStr(path));
return;
}
// index < len
String str = array[digits.charAt(index) - '0'];
for(int i = 0; i < str.length(); i ++) {
path.addLast(str.charAt(i));
mySol(digits, len, index + 1, path);
path.removeLast();
}
}
private String getStr(LinkedList<Character> path) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < path.size(); i ++) {
sb.append(path.get(i));
}
return sb.toString();
}
}