AUG!!! Fast solution in JAVA! With explaination


  • 0

    0_1468781558324_queeen.JPG

    public class Solution {
            static boolean[] exist;
    	static int len;
    	static int res;
    	public static int totalNQueens(int n) { 
    		if(n < 2)
    			return n;
    		len = 2*(n*2 - 1) + n;
    		exist = new boolean[len];
    		res = 0;
    		helper(0,n);
    		return res;
    	}
    	public static void helper(int level, int n){
    		if(level == n) {res++; return;}
    		for(int i = 0 ; i < n; i++)
    		{
    			int d1 = level - i + 3*n - 2;
    			int d2 = level + i;
    			if(exist[d1]||exist[d2]||exist[i+len - n])
    				continue;
    			exist[d1] = true;
    			exist[d2] = true;
    			exist[i+len - n] = true;
    			helper(level + 1, n);
    			exist[d1] = false;
    			exist[d2] = false;
    			exist[i+len - n] = false;
    				
    		}
    	}
    }
    

    Thumb up if you like it or leave your comments bellow to communicate.


Log in to reply
 

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