LeetCode N-Queens II

来源:互联网 发布:苹果mac使用 编辑:程序博客网 时间:2024/06/07 01:08

Follow up for N-Queens problem.

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

class Solution {public:int totalNQueens(int n) {vector<int> ivec;//初始化数组,使得 ivec[i] = ifor (int i = 0; i < n; ++i) {ivec.push_back(i);}int num = 0; func(num, ivec, 0, n);return num;}void func(int &num, vector<int> &ivec, int start, int last) {//判断是否到结尾,是就说明是全排列中的一种if (start == last) {//判断是否满足 皇后之间不能吃,斜对角线和反斜对角线for (int i = 0; i < last; ++i) {for (int j = i + 1; j < last; ++j) {if (i - j == ivec[i] - ivec[j] || j - i == ivec[i] - ivec[j])return;}}++num;return;}//循环加递归 做全排列for (int i = start; i < last; ++i) {swap(ivec[i], ivec[start]);func(num, ivec, start + 1, last);swap(ivec[i], ivec[start]);}}};



0 0
原创粉丝点击