当前位置: 首页 > article >正文

力扣 困难 52.N皇后II

文章目录

  • 题目介绍
  • 题解

题目介绍

在这里插入图片描述

题解

法一:返回51题N皇后List的长度
法二:


class Solution {
    private int n, ans;
    private boolean[] onPath, diag1, diag2;

    public int totalNQueens(int n) {
        this.n = n;
        onPath = new boolean[n];
        diag1 = new boolean[n * 2 - 1];
        diag2 = new boolean[n * 2 - 1];
        dfs(0);
        return ans;
    }

    private void dfs(int r) {
        if (r == n) {
            ans++; // 找到一个合法方案
            return;
        }
        for (int c = 0; c < n; c++) {
            int rc = r - c + n - 1;
            if (!onPath[c] && !diag1[r + c] && !diag2[rc]) {
                onPath[c] = diag1[r + c] = diag2[rc] = true;
                dfs(r + 1);
                onPath[c] = diag1[r + c] = diag2[rc] = false; // 恢复现场
            }
        }
    }
}


http://www.kler.cn/news/365272.html

相关文章:

  • sharpkeys-键盘部分按键不好用,用其它不常用按键代替
  • 使用 Pake 一键打包网页为桌面应用 / 客户端
  • 海港[NOIP2016]
  • 立志最细,FreeRtos中 中断、 调度器、的屏蔽/恢复,详解!!!
  • LVGL第二篇-组件创建与显示(以slider为例)
  • 国家能源集团携手海康威视研发攻克融合光谱煤质快检技术
  • 线性可分支持向量机的原理推导 9-28支持向量机优化中的可行性条件 公式解析
  • mysql的卸载与安装
  • 论文翻译 | A Prompt Pattern Catalog to Enhance Prompt Engineering with ChatGPT (下)
  • 【Javaee】网络原理—TCP协议的核心机制
  • 智能园艺:Spring Boot植物健康系统
  • Ubuntu 16上安装Go
  • 【数据分享】全国科技-产品质量国家监督抽查(1995-2021年)
  • TLS协议基本原理与Wireshark分析
  • HTTP Cookie深入解析
  • Java如何实现站内消息系统的设计与实现
  • frida脚本,自动化寻址JNI方法
  • 【论文+源码】基于spring boot的垃圾分类网站
  • YOLOv8改进,YOLOv8引入EffectiveSE注意力机制,二次创新C2f结构
  • 4K双模显示器7款评测报告
  • C++新增的类功能和可变参数模板
  • filebeat收集日志直接输出到elasticsearch
  • Redis的RDB执行原理
  • MyBatis 如何映射 Enum(使用 EnumTypeHandler、自定义 TypeHandler)
  • 判断特定时间点开仓的函数(编程技巧)
  • 程序结束、脚本语言、LISP、Python