leetCode 30天

题太难了,就来一个N皇后吧
51. N 皇后

cpp 复制代码
class Solution {
private:
    vector<vector<string>> res;
    void backtracking(int n, int row, vector<string>& chessboard){
        if (row == n){
            res.push_back(chessboard);
            return;
        }
        for (int col = 0; col<n; col++){
            if (isValid(row, col, chessboard, n)){
                chessboard[row][col] = 'Q';
                backtracking(n, row+1,chessboard);
                chessboard[row][col] = '.';
            }
        }
    }
    bool isValid(int row, int col, vector<string>& chessboard, int n){
        // 检查列
        for (int i = 0; i<row; i++){
            if (chessboard[i][col] == 'Q'){
                return false;
            }
        }
        // 检查45度角
        for (int i = row-1,j = col-1; i>=0 && j>=0; i--,j--){
            if (chessboard[i][j] == 'Q'){
                return false;
            }
        }
        // 检查135度
        for (int i = row-1,j = col+1; i>=0 && j<n; i--,j++){
            if (chessboard[i][j] == 'Q'){
                return false;
            }
        }
        return true;
    }

public:
    vector<vector<string>> solveNQueens(int n) {
        res.clear();
        vector<string> chessboard(n, string(n,'.'));
        backtracking(n, 0, chessboard);
        return res;
    }
};
相关推荐
laocui119 分钟前
Σ∆ 数字滤波
人工智能·算法
yzx99101333 分钟前
Linux 系统中的算法技巧与性能优化
linux·算法·性能优化
全栈凯哥1 小时前
Java详解LeetCode 热题 100(26):LeetCode 142. 环形链表 II(Linked List Cycle II)详解
java·算法·leetcode·链表
全栈凯哥1 小时前
Java详解LeetCode 热题 100(27):LeetCode 21. 合并两个有序链表(Merge Two Sorted Lists)详解
java·算法·leetcode·链表
SuperCandyXu1 小时前
leetcode2368. 受限条件下可到达节点的数目-medium
数据结构·c++·算法·leetcode
Humbunklung2 小时前
机器学习算法分类
算法·机器学习·分类
Ai多利2 小时前
深度学习登上Nature子刊!特征选择创新思路
人工智能·算法·计算机视觉·多模态·特征选择
蒟蒻小袁2 小时前
力扣面试150题--被围绕的区域
leetcode·面试·深度优先
Q8137574603 小时前
中阳视角下的资产配置趋势分析与算法支持
算法
yvestine3 小时前
自然语言处理——文本表示
人工智能·python·算法·自然语言处理·文本表示