My simple algorithm in Javascript


  • 0
    Y
    var letterCombinations = function(digits) {
        var mappings = [
            [],//0
            [],//1
            ['a', 'b', 'c'],
            ['d', 'e', 'f'],
            ['g', 'h', 'i'],
            ['j', 'k', 'l'],
            ['m', 'n', 'o'],
            ['p', 'q', 'r', 's'],
            ['t', 'u', 'v'],
            ['w', 'x', 'y', 'z']
        ];
        
        if(digits.length === 0)
            return [];
            
        if(digits.length === 1)
            return mappings[parseInt(digits)];
            
        var workingIndex = 1;
        var temp = mappings[parseInt(digits[0])];
        var ret = mappings[parseInt(digits[0])];
        var workingArray;
        do{
            
            workingArray = mappings[parseInt(digits[workingIndex])];
            temp = ret;
            ret = [];
            
            for(var i = 0; i < temp.length; i++){// ret =  ret * the third pair 
                for(var j = 0; j < workingArray.length; j++){
                    ret.push(temp[i] + workingArray[j]);
                }
            }
            
            workingIndex++;
        }while(workingIndex < digits.length);
        
        return ret;
    };

  • 0
    A

    You need to add values for 0 and 1 in the mappings array.


Log in to reply
 

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