javascript backtracking solution


  • 0
    /**
     * @param {number} n
     * @param {number} k
     * @return {number[][]}
     */
    var combine = function(n, k) {
        let res = [];
        helper(res,[],1,n);
        return res;
        
        function helper(res,tmp,start,n){
            if(tmp.length === k){
                //add copy of tmp array to the result
                res.push(tmp.slice());
                return;
            }
            for(let i = start; i <= n; i++){
                //ensure no-duplicate and acsending order in the tmp array
                if(tmp.length >= 1 && tmp[tmp.length-1] >= i) continue;
                tmp.push(i);
                //let start+1 to change the start item of each tmp array
                helper(res,tmp,start+1,n);
                tmp.pop();
            }
        }
    };
    
    

Log in to reply
 

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