public class Solution {
public List<String> letterCombinations(String digits) {
List<String> res = new LinkedList<>();
if (digits == null || digits.length() == 0) {
return res;
}
Map<Character, char[]> map = new HashMap<>();
map.put('0', new char[0]);
map.put('1', new char[0]);
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, digits, map, sb, 0);
return res;
}
private void helper(List<String> res, String digits, Map<Character, char[]> map, StringBuilder sb, int pos) {
if (sb.length() == digits.length()) {
res.add(new String(sb.toString()));
return;
}
for (int i = pos; i < digits.length(); i++) {
char num = digits.charAt(i);
char[] chars = map.get(num);
for (char c: chars) {
sb.append(c);
helper(res, digits, map, sb, i + 1);
sb.deleteCharAt(sb.length() - 1);
}
}
}
}
Letter Combinations of a Phone Number
最新推荐文章于 2025-07-20 11:42:00 发布