Javascript solution-sharing backtracking


  • 0
    C
    var combine = function(n, k) {
    	var solution = [];
    	var result = [];
    	var used = [];	// [1,2,...,n] each element can only be used once
    
    	var backTracking = function(n, m) {
    		if(m==k){
    			console.log(solution);
    			result.push(solution.slice(0));	// !result.push(solution)
    		}else{
    			for(var i=1; i<=n; ++i){
    				if(used[i]){ continue; }	// when true, express the element(used[i]) has been used
    				if(m>0 && solution[m-1]>i){ continue; }	// elements can only small to large order
    				used[i] = true;
    				solution[m] = i;
    				arguments.callee(n, m+1);	// backTracking(n, m+1)
    				used[i] = false;
    			}
    		}
    	}
    
    	backTracking(n, 0);
    
    	return result;
    };

Log in to reply
 

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