回溯算法:电话号码的字母组合

public class _17电话号码的字母组合_hot {
    public List<String> letterCombinations(String digits) {
        List<String> combinations = new ArrayList<>();
        if (digits.isEmpty()) {
            return combinations;
        }

        Map<Character, String> phoneMap = new HashMap<Character, String>() {{
            put('2', "abc");
            put('3', "def");
            put('4', "ghi");
            put('5', "jkl");
            put('6', "mno");
            put('7', "pqrs");
            put('8', "tuv");
            put('9', "wxyz");
        }};

        backtrack(combinations, phoneMap, digits, 0, "");
        return combinations;

    }

    public void backtrack(List<String> combinations,
                          Map<Character, String> phoneMap,
                          String digits, // 输入的参数
                          int index,  // 递归level
                          String combination) { //最后生成的参数

        // todo 1、terminator 满足结束条件
        if (index == digits.length()) {
            combinations.add(combination);
            return;
        }

        // todo 2、process 在选择列表里面做选择,backtrack之前做选择,backtrack撤销选择
        // 数字
        char digit = digits.charAt(index);
        // 字母
        String letters = phoneMap.get(digit);
        for (int i = 0; i < letters.length(); i++) {
            // todo 3、drill down,进入下一层
            backtrack(combinations, phoneMap, digits, index + 1, combination);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值