zoukankan      html  css  js  c++  java
  • 52. N皇后 II 深搜 位运算

    1. N皇后 II
      n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
      给定一个整数 n,返回 n 皇后不同的解决方案的数量。

    https://leetcode-cn.com/problems/n-queens-ii/

    void dfs(int n, int row, int col, int ld, int rd)n为总行数,row为当前行数,col为列,ld为左斜下,rd为右斜下
    (1 << n) - 1 生成n个1,1是可以放凰后的地方
    ~(col | ld | rd) col和ld和rd中的1表示不能放凰后,或操作完后再取反,1表示可以凰后的地方
    int bits = ~(col | ld | rd) & ((1 << n) - 1) 把这两个做与操作,现在bits表示真的可以放凰后的地方

    class Solution {
    public:
        int ans = 0;
        int totalNQueens(int n) {
            dfs(n, 0, 0, 0, 0);
            return ans;
        }
        void dfs(int n, int row, int col, int ld, int rd) {
            if (row >= n) {
                ans++;
                return;
            }
            int bits = ~(col | ld | rd) & ((1 << n) - 1);
            while (bits > 0) {
                int pick = bits & -bits;   //取最后一位1,其他位为0
                dfs(n , row + 1, col | pick, (ld | pick) << 1, (rd | pick) >> 1);
                bits = bits & (bits - 1);   //把最后一位变成0
            }
        }
    };
    
  • 相关阅读:
    SQL中存储过程与自定义函数的区别
    内置函数
    正则表达式
    HTML发展史
    触发器
    事务
    视图
    索引的使用
    存储过程和自定义函数的区别
    游标用法
  • 原文地址:https://www.cnblogs.com/xgbt/p/13832634.html
Copyright © 2011-2022 走看看