【LeetCode-Medium-Java】17. 电话号码的字母组合

题目:

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。

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

示例:

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

解题思路:回溯算法

1、每个字母代表的字母存放在map中

2、dfs记录到digits的第几个数字了cur,记录路径path,和最后的结果res。

3、注意:for循环循环的是分支的东西,也就是数字代表的各个字母...初学好懵。

扫描二维码关注公众号,回复: 13127115 查看本文章

代码:

public static List<String> letterCombinations(String digits) {
        if (digits.length() == 0) return new ArrayList<>();
        Map<Integer,String> map = new HashMap<>();
        map.put(2,"abc");
        map.put(3,"def");
        map.put(4,"ghi");
        map.put(5,"jkl");
        map.put(6,"mno");
        map.put(7,"pqrs");
        map.put(8,"tuv");
        map.put(9,"wxyz");

        List<String> res = new ArrayList<>();
        int cur = 0;
        String path = "";

        dfs(map,cur,digits,path,res);
        return res;
    }

    private static void dfs(Map<Integer,String> map, int cur, String digits, String path, List<String> res) {
        int len = digits.length();
        if (cur >=len) {
            res.add(path);
            return ;
        }

        String letters = map.get(digits.charAt(cur)-'0');
        for (int i = 0; i < letters.length(); i++) {
            path += letters.charAt(i);
            dfs(map,cur+1,digits,path,res);
            path = path.substring(0,path.length()-1);
        }
    }

回溯算法看起来简单,实际写代码的时候一些边界条件,循环条件...很难受

猜你喜欢

转载自blog.csdn.net/weixin_44284276/article/details/108690044