Javascript solution-sharing backtrack


  • 0
    C

    backtrack algori

    /**
     * @param {number[]} nums
     * @return {number[][]}
     * setp 1: each element can only be used once, so if(used[i]) { return false; }
     * setp 2: To solve the problem, in the letter cited a certain position, it is necessary to avoid the same letter has been filled. This prevents result in duplicate order.(Forgive me English, use google translate)
     */
    var permuteUnique = function(nums) {
    
    	nums.sort(function(val1, val2){
    	return val1>val2?1:val1<val2?-1:0;
    	});
    
    	var used = [];	// nums, each element can only be used once
    	var result = [];
    	var solution = [];
    
    	var backTracking = function(k) {
    		if(k==nums.length){
    			console.log(solution);
    			result.push(solution.slice(0));
    		}else{
    			var last = "";
    			for(var i=0; i<nums.length; ++i){
    				// console.log("i = "+i+"; solution = ["+solution+"]; nums["+i+"] = "+nums[i]);
    				if(used[i]) { continue; }	// when true, express the element(used[i]) has been used
    				if(last===nums[i]) { continue; }	// when nums[i-1] == nums[i], discard(x)
    				used[i] = true;
    				last = nums[i];
    				solution[k] = nums[i];
    				arguments.callee(k+1);	// backTracking(k+1);
    				used[i] = false;
    			}
    		}
    	};
    
    	backTracking(0);
    
    	return result;
    };
    
    permuteUnique([1, 1, 0]);
    

Log in to reply
 

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