public List<String> letterCombinations(String digits) {
List<String> res = new LinkedList<>();
if (digits == null || digits.length() == 0) {
return res;
}
Map<Integer, char[]> map = new HashMap<>();
map.put(1, new char[]{});
map.put(2, new char[]{'a', 'b', 'c'});
map.put(3, new char[]{'d', 'e', 'f'});
map.put(4, new char[]{'g', 'h', 'i'});
map.put(5, new char[]{'j', 'k', 'l'});
map.put(6, new char[]{'m', 'n', 'o'});
map.put(7, new char[]{'p', 'q', 'r', 's'});
map.put(8, new char[]{'t', 'u', 'v'});
map.put(9, new char[]{'w', 'x', 'y', 'z'});
StringBuilder sb = new StringBuilder();
helper(res, map, sb, 0, digits);
return res;
}
private void helper(List<String> res, Map<Integer, char[]> map, StringBuilder sb, int pos, String digits) {
if (sb.length() == digits.length()) {
res.add(sb.toString());
return;
}
for (int i = pos; i < digits.length(); i++) {
int n = digits.charAt(i) - '0';
char[] chars = map.get(n);
for (char c: chars) {
sb.append(c);
helper(res, map, sb, i + 1, digits);
sb.deleteCharAt(sb.length() - 1);
}
}
}Letter Combinations of a Phone Number
最新推荐文章于 2026-03-31 09:55:02 发布
本文介绍了一种通过递归算法实现电话号码对应的字母所有可能组合的方法。使用Java编程语言,结合哈希映射来存储数字到字母的对应关系,并利用递归函数进行组合生成。

1041

被折叠的 条评论
为什么被折叠?



