Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
Solution:
public class Solution {
Set<Integer> col = new HashSet<>();
Set<Integer> diag1 = new HashSet<>();
Set<Integer> diag2 = new HashSet<>();
public int totalNQueens(int n) {
return solve(0, n, 0);
}
public int solve(int row, int n, int count){
if(row==n) return count+1;
for(int c=0; c<n; c++){
if(col.contains(c) || diag1.contains(row+c) || diag2.contains(row-c)) continue;
col.add(c);
diag1.add(row+c);
diag2.add(row-c);
count = solve(row+1,n, count);
col.remove(c);
diag1.remove(row+c);
diag2.remove(row-c);
}
return count;
}
}