Leetcode HOT100 series – 17. Letter-comb-of-a-phone-number (DFS)

Time:2020-8-2

Title Description

Given a string containing only numbers 2-9, returns all combinations of letters it can represent.

Give the number to letter mapping as follows (same as the phone key). Note that 1 does not correspond to any letter.

Leetcode HOT100 series - 17. Letter-comb-of-a-phone-number (DFS)

Example:

Input: “23”
Output: [ad “,” AE “,” AF “,” BD “,” be “,” BF “,” CD “,” CE “,” CF “]

Thinking analysis

Textbook like DFS implementation
Leetcode HOT100 series - 17. Letter-comb-of-a-phone-number (DFS)
It’s ABC, and then they dock with def, depth first search, each path goes to the deepest, ad, ae… And it comes out naturally

The template pseudo code for DFS is as follows

dfs(information, pos, temp, result){
    If (depth is enough){
        result.add(temp);
        return;
    }
    for(;;;) {
        update_temp;
        dfs(information, pos + 1, new_temp, result);
    }
}

code implementation

class Solution {
    static Map<Character,String> letterDict = new HashMap();
    static {
        letterDict.put('2', "abc");
        letterDict.put('3', "def");
        letterDict.put('4', "ghi");
        letterDict.put('5', "jkl");
        letterDict.put('6', "mno");
        letterDict.put('7', "pqrs");
        letterDict.put('8', "tuv");
        letterDict.put('9', "wxyz");
    }
    
    public List<String> letterCombinations(String digits) {
        List<String> result = new ArrayList();
        if(digits == null || digits.length() == 0) {
            return result;
        }
        String temp = "";
        dfs(digits, 0, temp, result);
        return result;
    }
    
    private void dfs(String digits, int i, String temp, List<String> result) {
        if(i >= digits.length()) {
            result.add(temp);
            return;
        }
        char num = digits.charAt(i);
        String alphas = letterDict.get(num);
        for(int j = 0; j < alphas.length(); j++) {
            char c = alphas.charAt(j);
            DFS (digits, I + 1, temp + C, result); // consider multiplexing to save the space of temp
        }
    }
}

summary

Remember DFS,
DFS = loop recursion
The characteristic of DFS is that,

  1. The return value is void, which is returned by an external result
  2. Conditional transmission needs information about its DFS
  3. Position with current traversal
  4. There is an intermediate variable named temp to record the intermediate value of temp recorded after each DFS exploration

Recommended Today

ASP.NET Example of core MVC getting the parameters of the request

preface An HTTP request is a standard IO operation. The request is I, which is the input; the responsive o is the output. Any web development framework is actually doing these two things Accept the request and parse to get the parameters Render according to the parameters and output the response content So let’s learn […]