17. Letter Combinations of a Phone Number

Problem:
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.
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
3/26/2018 update:
Eliminate index and use stringbuilder will be faster.


class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> res = new ArrayList<>();
        String[] keys = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
        if (digits == null || digits.length() == 0) return res;
        dfs(res, new StringBuilder(), keys, digits);
        return res;
    }

    private void dfs(List<String> res, StringBuilder sb, String[] keys, String digits) {
        if (digits.length() == 0) {
            res.add(sb.toString());
            return;
        }

        String key = keys[digits.charAt(0) - '0'];
        for (char c: key.toCharArray()) {
            sb.append(c);
            dfs(res, sb, keys, digits.substring(1));
            sb.setLength(sb.length() - 1);
        }
    }
}

Analysis:
This problem should be categorized as easy. DFS, the sequence of digits determines level, the candidate chars under each digit determines nodes on the level.

Solution:


class Solution {
    private static final String[] KEYS = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
    public List<String> letterCombinations(String digits) {
        List<String> res = new ArrayList<>();
        if (digits == null || digits.length() == 0) return res;
        helper(res, 0, "", digits);
        return res;
    }
    
    private void helper(List<String> res, int index, String temp, String digits) {
        if (temp.length() == digits.length()) {
            res.add(temp);
            return;
        }
        
        String keys = KEYS[digits.charAt(index) - '0'];
        for (int i = 0; i < keys.length(); i++) {
            helper(res, index + 1, temp + keys.charAt(i), digits);
        }
    }
}

评论

此博客中的热门博文

776. Split BST

663. Equal Tree Partition

532. K-diff Pairs in an Array