[Leetcode 52, Hard] N Queens II
2015-07-21 02:29
453 查看
Problem:
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
Analysis:
Solutions:
C++:
Python:
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
Analysis:
Solutions:
C++:
bool IsSafeLean(int row, int col, vector<int> seizedColumns, int row_bound) { for(int i = 1; row - i >= 0 && col + i < row_bound; ++i) { if(seizedColumns[row - i] == col + i) return false; } for(int i = 1; row - i >= 0 && col - i >= 0; ++i) { if(seizedColumns[row - i] == col - i) return false; } return true; } void FindPlacements(vector<int> seizedColumns, int row, int row_bound, vector<vector<string> >& sols) { if(row == row_bound) { vector<string> placement; for(int i = 0; i < seizedColumns.size(); ++i) { string row = ""; for(int j = 0; j < row_bound; ++j) { if(j == seizedColumns[i]) row.push_back('Q'); else row.push_back('.'); } placement.push_back(row); } sols.push_back(placement); } else { for(int col = 0; col < row_bound; ++col) { if(!seizedColumns.empty()) { int index = 0; for(; index < seizedColumns.size(); ++index) { if(col == seizedColumns[index]) break; } if(index < seizedColumns.size() || (index == seizedColumns.size() && !IsSafeLean(row, col, seizedColumns, row_bound))) continue; } seizedColumns.push_back(col); FindPlacements(seizedColumns, row + 1, row_bound, sols); seizedColumns.erase(seizedColumns.end() - 1); } } } int totalNQueens(int n) { vector<vector<string> > sols; vector<int> seizedColumns; FindPlacements(seizedColumns, 0, n, sols); return sols.size(); }Java:
Python:
相关文章推荐
- UISegmentedControl的使用 IOS学习手记
- JAVA基础-GUI
- iOS开发-使用storyboard实现UILabel的自适应高度(iOS8)
- [Leetcode 63, Medium] Unique Paths II
- [Leetcode 62, Medium] Unique Paths
- ——JAVASE-GUI图形用户界面
- druid监控配置及sql注入防火墙配置
- iOS开发——UI进阶篇(二)自定义等高cell,xib自定义等高的cell,Autolayout布局子控件,团购案例
- UILabel 个人学习总结(一)
- unix环境高级编程书中实例缺少apue.h头文件解决方法
- rosbuild
- 第十二章、特殊权限SUID等详解
- UIImageView 简介
- 【Leetcode】Implement Queue using Stacks
- 杭电1005Number Sequence
- UIScrollView自动轮播图
- Hadoop 管理工具HUE配置-集成Unix用户和用户组
- UIScrollView实现不全屏分页的小技巧
- Android requestLayout 和 invalidate
- 玩转iOS 9的UIDynamics