lintcode-medium-N Queens II
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
Example
For n=4, there are 2 distinct solutions.
class Solution { /** * Calculate the total number of distinct N-Queen solutions. * @param n: The number of queens. * @return: The total number of distinct solutions. */ public int totalNQueens(int n) { //write your code here ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>(); if(n <= 0) return 0; int[] position = new int[n]; helper(result, 0, position, n); return result.size(); } public void helper(ArrayList<ArrayList<String>> result, int row, int[] position, int n){ if(row == n){ ArrayList<String> solution = new ArrayList<String>(); for(int i = 0; i < n; i++){ StringBuilder line = new StringBuilder(); for(int j = 0; j < n; j++){ if(j == position[i]) line.append('Q'); else line.append('.'); } solution.add(line.toString()); } result.add(new ArrayList<String>(solution)); return; } for(int i = 0; i < n; i++){ position[row] = i; if(valid(position, row, n)) helper(result, row + 1, position, n); } return; } public boolean valid(int[] position, int row, int n){ for(int i = row - 1; i >= 0; i--){ if(position[row] == position[i] || Math.abs(position[row] - position[i]) == row - i) return false; } return true; } };