JavaScript backtracking solution to print all the permutations


  • 0
    D
    
    /**
     * @param {number} N
     * @return {number}
     */
    var countArrangement = function(N) {
        
        var count = 0;
        var hashMap = {};
        function solve(N, k, arr){
          
        	if(arr.length === N + 1){
                count++;
                // console.log(arr); // print all the permutations
        		return;
        	}
        
        	for(let i = 1; i <= N; i++){
        	    
        	
            
                if(hashMap[i]){
                    continue;
                }
              
              if(k % i === 0 || i % k === 0){
                arr[k] = i;
                hashMap[i] = true;
                solve(N, k + 1, arr);
                
                // backtrack
                arr.pop(); 
                hashMap[i] = false;;
              }
        	}
          
        }
        
        
        solve(N, 1, []);
        	
        return count;
    
    
    };
    
    
    

Log in to reply
 

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