leetcode-电话号码的字母组合

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

示例 1:

输入:digits = "23"

输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]

示例 2:

输入:digits = "2"

输出:["a","b","c"]

提示:

1 <= digits.length <= 4

digits[i] 是范围 ['2', '9'] 的一个数字。

思路 :考虑两点。第一点,当前数字考虑后是否还会被考虑?第二点,遍历的位置?第一点,当前数字对应字母情况考虑后,不会再被考虑。第二点,每次考虑当前数字即可。

综上,dfs中使用index考虑当前数字的情况,下一个数字的情况用index+1考虑。
代码

c 复制代码
class Solution {
    Map<Integer,String> phoneKey = new HashMap<>();
    public List<String> letterCombinations(String digits) {
        phoneKey.put(2,"abc");
        phoneKey.put(3,"def");
        phoneKey.put(4,"ghi");
        phoneKey.put(5,"jkl");
        phoneKey.put(6,"mno");
        phoneKey.put(7,"pqrs");
        phoneKey.put(8,"tuv");
        phoneKey.put(9,"wxyz");
        List<String> res = new ArrayList<>();
        dfs(digits, 0, "", res);
        return res;

    }

    public void dfs(String digits, int index, String temp, List<String> res){
        if(index==digits.length()){
            res.add(temp);
            return;
        }
		// 当前数字可以表示的字母情况
        String s = phoneKey.getOrDefault(Integer.parseInt(String.valueOf(digits.charAt(index))),"");
        for(int i = 0;i<s.length();i++){
            dfs(digits, index+1,temp+s.charAt(i),res);
        }
    }
}
相关推荐
We་ct3 小时前
LeetCode 236. 二叉树的最近公共祖先:两种解法详解(递归+迭代)
前端·数据结构·算法·leetcode·typescript
小白菜又菜3 小时前
Leetcode 229. Majority Element II
算法·leetcode·职场和发展
Frostnova丶3 小时前
LeetCode 1461. 检查一个字符串是否包含所有长度为 K 的二进制子串
算法·leetcode·哈希算法
历程里程碑4 小时前
普通数组---合并区间
java·大数据·数据结构·算法·leetcode·elasticsearch·搜索引擎
Felven4 小时前
B. 250 Thousand Tons of TNT
算法
victory04314 小时前
PPO GAE优势函数演化和推导
算法
Jasmine_llq5 小时前
《P3572 [POI 2014] PTA-Little Bird》
算法·滑动窗口·单调队列·动态规划(dp)·多组查询处理·循环优化(宏定义 rep)
tankeven5 小时前
HJ101 排序
c++·算法
流云鹤5 小时前
动态规划02
算法·动态规划