题目描述
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
思路
思路:递归。
在dfs中,枚举当前数字的所有可能,并进入下一个数字的递归。
代码
class Solution {
// Mapping集合
private static final String[] MAPPING = new String[]{"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
// 结果
private final List<String> res = new ArrayList<>();
// 输入digits
private char[] digits;
// 当前结果paths
private char[] paths;
public List<String> letterCombinations(String digits) {
int n = digits.length();
if (n == 0) {
return List.of();
}
// 初始化
this.digits = digits.toCharArray();
// 从0开始
paths = new char[n];
dfs(0);
return res;
}
private void dfs(int i) {
// 长度到了,保存结果并return
if (i == digits.length) {
res.add(new String(paths));
return ;
}
// 遍历每一种可能的字符,不断地递归
for (char c : MAPPING[digits[i] - '0'].toCharArray()) {
paths[i] = c;
dfs(i + 1);
}
}
}