题目描述
给定一个仅包含数字 2-9
的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
说明:
尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。
解题思路
- 对数字字母之间进行映射,我这里使用二维数组,也可以使用Map;
- 利用dfs从头到尾搜索字符串,映射为对应字母,当到达末尾时加入字符串即可;
代码如下:
class Solution {
private char[][] letters = {{}, {},
{'a', 'b', 'c'}, {'d', 'e', 'f'}, {'g', 'h', 'i'}, {'j', 'k', 'l'},
{'m', 'n', 'o'}, {'p', 'q', 'r', 's'}, {'t', 'u', 'v'}, {'w', 'x', 'y', 'z'}
};
private List<String> combinations = new ArrayList<>();
public List<String> letterCombinations(String digits) {
if(digits.length() > 0) dfs(0, digits, "");
return combinations;
}
private void dfs(int index, String digits, String s){
if(index >= digits.length()){
combinations.add(s);
return;
}
int k = digits.charAt(index) - '0';
for(int i = 0; i < letters[k].length; i++){
dfs(index + 1, digits, s + letters[k][i]);
}
}
}
欢迎访问我的GitHub题解查看其它题解,一起加油