解题思路
与n-queens差不多,只不过row == n时不需要存储结果只需要将解法计数加一。
代码
class Solution {
public:int choose[10001];void dfs(int &res,int row,int n){if(row == n){res++;}else{for(int i = 0;i < n;i++){choose[row] = i;bool flag = true;for(int j = 0;j < row;j++){if(choose[j] == choose[row] || row - j == choose[j] - choose[row] || row - j == choose[row] - choose[j]){flag = false;break;}}if(flag)dfs(res,row + 1,n);}}}int totalNQueens(int n) {int res = 0;memset(choose,-1,sizeof(choose));dfs(res,0,n);return res;}
};