Letter Combinations of a Phone Number

本文介绍了一种通过递归算法实现电话号码对应的字母所有可能组合的方法。使用Java编程语言,结合哈希映射来存储数字到字母的对应关系,并利用递归函数进行组合生成。
public List<String> letterCombinations(String digits) {
        List<String> res = new LinkedList<>();
        if (digits == null || digits.length() == 0) {
            return res;
        }
        Map<Integer, char[]> map = new HashMap<>();
        map.put(1, new char[]{});
        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'});
        StringBuilder sb = new StringBuilder();
        helper(res, map, sb, 0, digits);
        return res;
    }
    
    private void helper(List<String> res, Map<Integer, char[]> map, StringBuilder sb, int pos, String digits) {
        if (sb.length() == digits.length()) {
            res.add(sb.toString());
            return;
        }
        for (int i = pos; i < digits.length(); i++) {
            int n = digits.charAt(i) - '0';
            char[] chars = map.get(n);
            for (char c: chars) {
                sb.append(c);
                helper(res, map, sb, i + 1, digits);
                sb.deleteCharAt(sb.length() - 1);
            }
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值