【LeetCode】52. N-Queens II
2024-09-22 02:41:44
N-Queens II
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
简单的回溯法。
cur[i] == j 代表第i行的皇后位于第j列。
对于每一行,尝试所有列,
如果当前行尝试的位置不与前面所有行的位置冲突,则可以递归到下一行。
class Solution {
public:
int totalNQueens(int n) {
int count = ;
vector<int> cur;
Helper(count, cur, , n);
return count;
}
void Helper(int& count, vector<int> cur, int pos, int n)
{
if(pos == n)
count ++;
else
{
for(int i = ; i < n; i ++)
{
cur.push_back(i);
if(check(cur))
Helper(count, cur, pos+, n);
cur.pop_back();
}
}
}
bool check(vector<int> cur)
{
int size = cur.size();
int loc = cur[size-];
for(int i = ; i < size-; i ++)
{
//never same row //col
if(cur[i] == loc)
return false; //diag
if(abs(cur[i]-loc) == abs(i-size+))
return false;
}
return true;
}
};
最新文章
- 手机游戏渠道SDK接入工具项目分享(三)拨开云雾是个坑
- protobuf学习(1)-ubuntu14.04下protobuf2.6安装
- 20145308刘昊阳 《Java程序设计》实验三 敏捷开发与XP实践 实验报告
- Three.js基础探寻十——动画
- 【转】COCOS2D-X之不断变化的数字效果Demo
- RandomAccessFile类的使用(随机读取java中的文件)
- 欢迎使用skymvc框架,简单易用的php框架
- Android Dev
- VC2010的破解方法(针对旗舰版)
- 设置TextView的密码效果以及跑马灯效果
- 【学习opencv第六篇】图像的反转操作
- linuxCentOs6前期简单且必要的设置
- Mybatis基础学习(三)&mdash;映射文件
- 华科机考:a+b
- LOCAL_EXPORT_&#215;&#215;用法
- Row_Number() over()
- kafka安装与简单使用
- 针对Nginx日志的相关运维操作记录
- 【sql】之case when then else end
- ICE简介及C++程序例子(转)