AC java concise solution


  • 0
    F
    public class Solution {
        int res;
        public int totalNQueens(int n) {
            helper(0,new int[n]);
            return res;
        }
        
        private void helper(int r, int[] state)
        {   
            if(r==state.length) res++;
            else{
                for(int c=0;c<state.length;c++)
                {
                    if(isValid(state,c,r)){
                        state[r] = c;
                        helper(r+1,state);
                    }
                }
            }
        }
        
        private boolean isValid(int[] state, int c, int r)
        {
            for(int i=0;i<r;i++)
                if(state[i]==c||Math.abs(c-state[i])==(r-i))
                    return false;
            return true;
        }
    }

Log in to reply
 

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