27 lines javascript dfs beats 94%


  • 0
    var letterCombinations = function(digits) {
    	if (digits.length === 0) {
    		return [];
    	}
    	var map = {
    		"2": ["a", "b", "c"],
    		"3": ["d", "e", "f"],
    		"4": ["g", "h", "i"],
    		"5": ["j", "k", "l"],
    		"6": ["m", "n", "o"],
    		"7": ["p", "q", "r", "s"],
    		"8": ["t", "u", "v"],
    		"9": ["w", "x", "y", "z"]
    	};
    	var rtn = [];
    	var dfs = function(digitIndex, word) {
    		if (digitIndex < digits.length) {
    			var letter = digits[digitIndex];
    			map[letter].forEach(function(letter) {
    				dfs(digitIndex + 1, word + letter);
    			});
    		} else {
    			rtn.push(word);
    		}
    	}
    	dfs(0, "");
    	return rtn;
    };

Log in to reply
 

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