N-Queens II 解答

时间:2021-06-24 16:55:08

Question

Follow up for N-Queens problem.

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

N-Queens II 解答

Solution

This problem seems like 2D DP, but it is not.

For DP problem, usually we will have a/ some directions. But here, we can go to all four directions. So this can not be solved by DP.

We still use the way to implement N-Queens.

There is one stuff worth mentioning:

In java, if in function f(x), we pass a variable x of primitive data type like int into a function g(x), the value of x in f(x) is not changed.

If we want it to be modified, we need to pass a reference.

 public class Solution {

     public int totalNQueens(int n) {
// Should use an object rather than a int variable here
// We want "result" to be modified in helper function
int[] result = {0};
int[] queen = new int[n];
helper(n, 0, queen, result);
return result[0];
} private void helper(int n, int rowNum, int[] queen, int[] result) {
if (n == rowNum) {
result[0]++;
return;
} for (int i = 0; i < n; i++) {
queen[rowNum] = i;
if (check(rowNum, queen))
helper(n, rowNum + 1, queen, result);
}
} private boolean check(int rowNum, int[] queen) {
int colNum = queen[rowNum];
for (int i = 0; i < rowNum; i++) {
if ((colNum == queen[i]) || (queen[i] - i == colNum - rowNum) || (queen[i] + i == colNum + rowNum))
return false;
}
return true;
}
}