【重点】【DFS】17.电话号码的组合

发布时间:2023年12月18日

题目

法1:DFS

class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> res = new ArrayList<>();
        if (digits.length() == 0) {
            return res;
        }
        List<Integer> digitList = new ArrayList<>();
        for (int i = 0; i < digits.length(); ++i) {
            digitList.add(digits.charAt(i) - '0');
        }
        Map<Integer, char[]> map = new HashMap<>();
        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'});
        char[] tmp = new char[digitList.size()];
        dfs(map, digitList, 0, tmp, res);

        return res;
    }

    public void dfs(Map<Integer, char[]> map, List<Integer> digitList, 
                    int index, char[] tmp, List<String> res) {
        if (index == digitList.size()) {
            res.add(String.valueOf(tmp));
            return;
        }
        char[] charArray = map.get(digitList.get(index));
        int curSize = charArray.length;
        for (int i = 0; i < curSize; ++i) {
            tmp[index] = charArray[i];
            dfs(map, digitList, index + 1, tmp, res);
        }
    }
}
文章来源:https://blog.csdn.net/Allenlzcoder/article/details/135069990
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。