Javascript, solution-sharing, backtracking


  • 0
    C
    [javascript]
    /**
     * step 1: digits to numArray // var digits="23"; numArray=['2','3'];
     * step 2: numArray to stringArray // var stringArray=[]; stringArray.push(numToString(numArray[i])); stringArray=["abc","def"];
     * step 3: backTacking  function
     */
    var letterCombinations = function(digits) {
    	if(!digits) { return []; }
    	function numToString(digit) {
    		switch (digit) {
    			case "0": return " ";
    			case "1": return "";
    			case "2": return "abc";
    			case "3": return "def";
    			case "4": return "ghi";
    			case "5": return "jkl";
    			case "6": return "mno";
    			case "7": return "pqrs";
    			case "8": return "tuv";
    			case "9": return "wxyz";
    		}
    	}
    	var numArray = digits.split(""); // step 1
    	var stringArray = [];
    	var result = [];
    	var str = "";
    	for(var i=0; i<numArray.length; i++){ // step 2
    		stringArray.push(numToString(numArray[i]));
    	}
    	// console.log("numArray=["+numArray+"]; numArray.length="+numArray.length+"; stringArray=["+stringArray+"];");
    	var backTracking = function (m, n) { // step 3
    		if(m==n){
    			// console.log("str="+str+";");
    			return result.push(str);
    		}else{
    			for(var i=0; i<stringArray[m].split("").length; i++){
    				// console.log("stringArray["+m+"]["+i+"]="+stringArray[m][i]+";");
    				str += "" + stringArray[m][i];
    				backTracking(m+1, n);
    				str = str.substr(0, str.length-1);
    			}
    		}
    	}
    	backTracking(0, numArray.length);
    	return result;
    }
    letterCombinations("");
    letterCombinations("22");
    letterCombinations("239");

Log in to reply
 

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