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;
}
};

最新文章

  1. 手机游戏渠道SDK接入工具项目分享(三)拨开云雾是个坑
  2. protobuf学习(1)-ubuntu14.04下protobuf2.6安装
  3. 20145308刘昊阳 《Java程序设计》实验三 敏捷开发与XP实践 实验报告
  4. Three.js基础探寻十——动画
  5. 【转】COCOS2D-X之不断变化的数字效果Demo
  6. RandomAccessFile类的使用(随机读取java中的文件)
  7. 欢迎使用skymvc框架,简单易用的php框架
  8. Android Dev
  9. VC2010的破解方法(针对旗舰版)
  10. 设置TextView的密码效果以及跑马灯效果
  11. 【学习opencv第六篇】图像的反转操作
  12. linuxCentOs6前期简单且必要的设置
  13. Mybatis基础学习(三)&mdash;映射文件
  14. 华科机考:a+b
  15. LOCAL_EXPORT_&#215;&#215;用法
  16. Row_Number() over()
  17. kafka安装与简单使用
  18. 针对Nginx日志的相关运维操作记录
  19. 【sql】之case when then else end
  20. ICE简介及C++程序例子(转)

热门文章

  1. ldap客户端以及jenkins的配置
  2. Mongodb安全认证及Java调用
  3. nth-digit
  4. [Python爬虫]煎蛋网OOXX妹子图爬虫(1)——解密图片地址
  5. Android中的树状(tree)列表
  6. 【注解】Annotation Target ElementType
  7. 时间插件WdatePicker使用方法
  8. python3 使用openpyxl库读写excel(续)
  9. Dijkstra(迪杰斯特拉)算法求解最短路径
  10. svmtrain princomp 出现的问题