Letter Combinations of a Phone Number

https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/

Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.

Thoughts

要返回all combinations, 想到DFS或BFS. BFS存path即可, 把每一位的所有可能加进去.

Code

class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> res = new ArrayList<>();
        if (digits.length() == 0) {
            return res;
        }
        Map<Character, 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");

        Queue<String> queue = new LinkedList<>();
        queue.offer("");

        for (int i = 0; i < digits.length(); i++) {
            int size = queue.size();
            for (int j = 0; j < size; j++) {
                String path = queue.poll();
                String str = map.getOrDefault(digits.charAt(i), "");
                for (int k = 0; k < str.length(); k++) {
                    queue.offer(path + str.charAt(k));
                }
            }
        }

        int size = queue.size();
        for (int j = 0; j < size; j++) {
            String path = queue.poll();
            res.add(path);
        }

        return res;
    }
}

Analysis

时间复杂度为指数级.

Last updated