AcWing
  • 首页
  • 课程
  • 题库
  • 更多
    • 竞赛
    • 题解
    • 分享
    • 问答
    • 应用
    • 校园
  • 关闭
    历史记录
    清除记录
    猜你想搜
    AcWing热点
  • App
  • 登录/注册

LeetCode 17. Letter Combinations of a Phone Number    原题链接    简单

作者: 作者的头像   RecSys ,  2025-05-13 18:22:14 · 上海 ,  所有人可见 ,  阅读 3


0


class Solution {
    // DFS
    List<String> res = new ArrayList<>();
    StringBuilder path = new StringBuilder();// StringBuilder
    Map<Character, String> phoneMap = new HashMap<>(){{//哈希
        put('2', "abc");
        put('3', "def");
        put('4', "ghi");
        put('5', "jkl");
        put('6', "mno");
        put('7', "pqrs");
        put('8', "tuv");
        put('9', "wxyz");
    }};
    public List<String> letterCombinations(String digits) {
        if(digits.length() == 0){
            return res;
        }
        dfs(digits, 0);
        return res;
    }
    private void dfs(String digits, int idx){
        if(idx == digits.length()){
            res.add(path.toString());// toString
            return;
        }
        char c = digits.charAt(idx);
        String letter = phoneMap.get(c);
        for(int i = 0; i < letter.length(); i++){
            path.append(letter.charAt(i));
            dfs(digits, idx + 1);
            path.deleteCharAt(idx);//恢复现场
        }
    }
}

0 评论

App 内打开
你确定删除吗?
1024
x

© 2018-2025 AcWing 版权所有  |  京ICP备2021015969号-2
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息