LeetCode:N-Queens II
2016-06-08 18:46
615 查看
N-Queens II
Total Accepted: 45401 TotalSubmissions: 114053 Difficulty: Hard
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
Subscribe to see which companies asked this question
Hide Tags
Backtracking
Hide Similar Problems
(H) N-Queens
思路:
由于N个皇后的任意两个不能处在同一行,那么这肯定是每一个皇后占据一行。于是我们可以定义一个数组nums
,数组中第i个数字表示位于第i行的皇后的列号。先把nums的N个数字分别用0~N-1初始化,接下来我们要做的事情就是对数组nums做全排列。由于我们是用不同的数字初始化数组中的数字,因此任意两个皇后肯定不同列。我们只需要判断得到的每一个排列对应的N个皇后是不是在同一对角斜线上,也就是数组的两个下标i和j,是不是i-j==nums[i]-nums[j]或者j-i==nums[i]-nums[j]。
因此实际上就是在(元重复元素)全排列(参考:LeetCode:Permutations)的基础上多了一个判断而已。
c++ code:
class Solution {
public:
int totalNQueens(int n) {
vector<int> nums(n);
for(int i=0;i<n;i++)
nums[i]=i;
int count = 0;
permute(nums, 0 ,count);
return count;
}
// 自定义函数
void permute(vector<int> &nums, int pos, int &count) {
int n = nums.size();
if(pos==n) {
if(check(nums))
count++;
return;
}
for(int i=pos;i<n;i++) {
swap(nums[pos], nums[i]);
permute(nums, pos+1, count);
swap(nums[i], nums[pos]);
}
}
bool check(vector<int> &nums) {
int n = nums.size();
for(int i=0;i<n;i++) {
for(int j=i+1;j<n;j++)
// 判断是否在主、副对角线上
if(i-j == nums[i]-nums[j] || j-i == nums[i]-nums[j])
return false;
}
return true;
}
};
相关文章推荐
- 有关StringBuilder字符串的一些应用
- Looper、Message、MessageQueue、Handler异步消息处理机制源码分析
- 检测预设资源是否有UIFont为空的编辑器
- Android学习之图解调用invalidate()和requestLayout()的过程
- Parquet 读写
- 栈(stack)和队列(queue)的简单实例
- UIAlertController
- UIView的drawRect调用时机和条件
- 栈和队列的简单实例
- RequireJS入门(一)
- BearSkill之UIView挖空处理
- ios UIView常用动画效果
- 关于easyui 行高禁止自适应
- Android中常用的handler进行UI更新和Thread代码
- .MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1
- while(true)引发的Dubbo应用假死
- iOS巅峰之UILabel上显示不同的字体样式和颜色
- UIFont 字体样式 [UIFont fontWithName~];
- libevent windows build
- hdu 1005 Number Sequence(循环节)