Topic describes

Their thinking

  • In this case, DFS is used to solve the problem.
  • And the thing about recursion is that there’s a loop.
  • The DFS function takes two arguments, the current string and a pointer, and when the pointer exceeds the length of digits, it is saved and returned, and then loops through the next character, which is really cool.

The problem solving code

var letterCombinations = function(digits) {
    // Boundary conditions
    if (digits === ' ') return [];
    // Build a hash table for characters from 2 to 9
    const m = new Map(a); m.set('2'.'abc');
    m.set('3'.'def');
    m.set('4'.'ghi');
    m.set('5'.'jkl');
    m.set('6'.'mno');
    m.set('7'.'pqrs');
    m.set('8'.'tuv');
    m.set('9'.'wxyz');
    
    // Define the returned array
    const res = [];
    // The idea of using DFS
    function dfs(str,pointer) {
        // End condition of recursion
        if (pointer > digits.length-1) {
            res.push(str);
            return;
        }
        let letters = m.get(digits[pointer]);
        for (let v of letters) {
            dfs(str + v,pointer + 1);
        }
        return;
    }
    dfs(' '.0)
    return res
};
Copy the code

revelation

  • Learn the idea of DFS.
  • Adding loops to DFS is a good way to solve these problems.

Refer to the link

Leetcode-cn.com/problems/le…