题目:
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
思路:与N queens 一样
代码:
class Solution { public: bool isOK(vector<int> oneSolution, int k, int val){ for (int i=0; i<k; i++){ if (oneSolution[i] == val) return false; else if (abs(val-oneSolution[i]) == abs(i-k)) return false; } return true; } void backtracking(vector<int> oneSolution, int k, int n, int &count){ if (k == n) { count+=1; } else{ k = k+1; for (int i=0; i<n; i++){ if (!isOK(oneSolution, k-1, i)) continue; oneSolution[k-1] = i; backtracking(oneSolution, k, n, count); } } } int totalNQueens(int n) { // Start typing your C/C++ solution below // DO NOT write int main() function int k = 0; vector<int> oneSolution(n); int count = 0; backtracking(oneSolution, k, n, count); return count; } };