leetcode - N-Queens II
LeetCode II queens
2023-09-14 09:06:24 时间
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
class Solution { private: int res; public: int totalNQueens(int n) { std::vector<int> state(n, -1); res = 0; dfs(state, 0); return res; } void dfs(std::vector<int> &state, int row) { int n = state.size(); if(row == n) { res++; return; } for(int col = 0; col < n; col++) if(isValid(state, row, col)) { state[row] = col; dfs(state, row+1); state[row] = -1;; } } bool isValid(std::vector<int> &state, int row, int col) { for(int i = 0; i < row; i++) if(state[i] == col || abs(row - i) == abs(col - state[i])) return false; return true; } };
相关文章
- Java实现 LeetCode 657 机器人能否返回原点(暴力大法)
- Java实现 LeetCode 526 优美的排列(DFS)
- Java实现 LeetCode 516 最长回文子序列
- Java实现 LeetCode 235 二叉搜索树的最近公共祖先
- Java实现 LeetCode 213 打家劫舍 II(二)
- Java实现 LeetCode 140 单词拆分 II(二)
- Java实现 LeetCode 132 分割回文串 II(二)
- Java实现 LeetCode 122 买卖股票的最佳时机 II
- Java实现 LeetCode 25 K个一组翻转链表
- Java实现 LeetCode 19删除链表的倒数第N个节点
- LeetCode(117):填充同一层的兄弟节点 II
- LeetCode(82):删除排序链表中的重复元素 II
- LeetCode(40):组合总和 II
- LeetCode(32):最长有效括号
- [LeetCode] Search a 2D Matrix II
- LeetCode-707. 设计链表【单链表,双链表】
- LeetCode-1758. 生成交替二进制字符串的最少操作数【字符串,三行代码!】
- LeetCode-937. 重新排列日志文件【stable_sort(),自定义排序】
- 518. 零钱兑换 II ——【Leetcode每日一题】
- leetcode算法第9题
- [LeetCode]N-Queens II
- 【Leetcode刷题Python】122.买卖股票的最佳时机 II
- 【Leetcode刷题Python】63. 不同路径 II
- 【LeetCode】695.岛屿的最大面积
- 【LeetCode】剑指 Offer II 107. 矩阵中的距离