0%

LeetCode-17

题目

结果

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
private static final Map<Character, List<Character>> num2Alpha = new HashMap<>();
private static final StringBuilder combination = new StringBuilder();

private void initMap() {
num2Alpha.put('2', List.of('a', 'b', 'c'));
num2Alpha.put('3', List.of('d', 'e', 'f'));
num2Alpha.put('4', List.of('g', 'h', 'i'));
num2Alpha.put('5', List.of('j', 'k', 'l'));
num2Alpha.put('6', List.of('m', 'n', 'o'));
num2Alpha.put('7', List.of('p', 'q', 'r', 's'));
num2Alpha.put('8', List.of('t', 'u', 'v'));
num2Alpha.put('9', List.of('w', 'x', 'y', 'z'));
}

public List<String> letterCombinations(String digits) {
List<String> ans = new LinkedList<>();
if (digits.length() == 0) {
return ans;
}
initMap();
backtrack(ans, digits, 0);
return ans;
}

private void backtrack(List<String> ans, String digits, int index) {
if (index == digits.length()) {
ans.add(combination.toString());
return;
}
var letters = num2Alpha.get(digits.charAt(index));
for (Character letter : letters) {
combination.append(letter);
backtrack(ans, digits, index + 1);
combination.deleteCharAt(index);
}
}
}

复杂度

时间复杂度:O(∏数字对应字母的个数),需要遍历每一种字母组合

空间复杂度:O(digits.length),Map的大小可以视为常数,所以空间复杂度主要取决于递归层数。