N-Queens II

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

N-Queens II - 图1

Solution:

  1. public class Solution {
  2. int count;
  3. public int totalNQueens(int n) {
  4. count = 0;
  5. helper(n, 0, new int[n]);
  6. return count;
  7. }
  8. private void helper(int n, int row, int[] columnForRow) {
  9. if (row == n) {
  10. count++;
  11. return;
  12. }
  13. for (int col = 0; col < n; col++) {
  14. columnForRow[row] = col;
  15. if (check(row, col, columnForRow)) {
  16. helper(n, row + 1, columnForRow);
  17. }
  18. }
  19. }
  20. private boolean check(int row, int col, int[] columnForRow) {
  21. for (int r = 0; r < row; r++) {
  22. if (columnForRow[r] == col || row - r == Math.abs(columnForRow[r] - col)) {
  23. return false;
  24. }
  25. }
  26. return true;
  27. }
  28. }