N-Queens II DFS
2015-07-06 11:03
549 查看
思路:
DFS。与上一题相同,直接求出解的个数即可。不必记录所有的解。
时间复杂度O(N!),空间复杂度O(N)。
DFS。与上一题相同,直接求出解的个数即可。不必记录所有的解。
时间复杂度O(N!),空间复杂度O(N)。
class Solution { private: int ans = 0; bool canSet(vector<int> &map, int n, int row, int col) { for(int tmprow = 0; tmprow < row; ++tmprow) { int tmpcol = map[tmprow]; if(tmpcol == col) // row return false; if((tmpcol - col) == (tmprow - row)) // right slant line return false; if((tmpcol - col) == (row - tmprow)) // left slant line return false; } return true; } void dfs(vector<int> &map, int n, int row) { for(int i = 0; i < n; ++i) { if(canSet(map, n, row, i)) { map[row] = i; if(row == n - 1) { ++ans; map[row] = 0; return; } dfs(map, n, row+1); map[row] = 0; } } } public: int totalNQueens(int n) { vector<int> map = vector<int>(n, 0); dfs(map, n, 0); return ans; } };
相关文章推荐
- 利用HTML实现软件的UI
- UIDatePicker简单使用
- UITextView的内容长度限制
- IOS入门学习笔记(普通UI控件--UIButton)
- kernel build
- unique-paths-ii
- N-Queens DFS
- Arduino Uno 在win7 64位下的驱动问题
- DAX Tabular Calculate,Filter,Value和All
- 优先队列priority_queue 用法详解
- UIDynamicAnimator 小结
- 从源代码的角度聊聊java中StringBuffer、StringBuilder、String中的字符串拼接
- 从源代码的角度聊聊java中StringBuffer、StringBuilder、String中的字符串拼接
- ScrollView中添加一个android:fillViewport="true"(转)
- (PHP 5.3 and above) Please set ‘request_order’ ini value to include C,G and P (recommended: ‘CGP’) i
- [SoapUI] 获取Cookie,并循环遍历当前Project下所有的Test Suite,Test Case,Test Step,将Cookie传递给这些Test Step
- unique-paths
- 详解 UIView 的 Tint Color 属性
- 自定义UI之ActionBar
- Ubuntu更新包管理器失败:Requires installation of untrusted packages问题解决