JavaScript BFS


  • 0
    G
    const digitToLetters = {
        '2': 'abc',
        '3': 'def',
        '4': 'ghi',
        '5': 'jkl',
        '6': 'mno',
        '7': 'pqrs',
        '8': 'tuv',
        '9': 'wxyz'
    }
     
    var letterCombinations = function(digits) {
        if (digits.length === 0) return [];
        
        let queue = [''];
        
        for (let i = 0; i < digits.length; i++) {
            const newQueue = [];
            const letters = digitToLetters[digits.charAt(i)];
    
            for (let j = 0; j < letters.length; j++)
                for (let k = 0; k < queue.length; k++)
                    newQueue.push(queue[k] + letters.charAt(j));
            
            queue = newQueue;
        }
        
        return queue;
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.