LeetCode:17。電話番号の文字の組み合わせ
各キー(数字)は複数の文字に対応し、すべて配置された再帰的なdf
ハッシュテーブルを使用して、各キーの文字を保存します
ACコード
class Solution {
public void init(Map<Integer, char[]> map){
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'});
}
List<String> list = new ArrayList<>();
Map<Integer, char[]> map = new HashMap<>();
public List<String> letterCombinations(String digits) {
if("".equals(digits)) return list;
init(map);
char[] cs = digits.toCharArray();
dfs(cs, 0, "");
return list;
}
public void dfs(char[] cs, int s, String str){
if(s >= cs.length) {
list.add(str);
return ;
}
char [] c = map.get(cs[s] - '0');
int len = c.length;
for(int i = 0; i < len; i++) {
// 遍历所有的字母
dfs(cs, s + 1, str + c[i]);
}
}
}