52.N皇后II(N-Queens II)

LeetCode-52. N-Queens II (JAVA)(N皇后解集个数) 阅读详情

题目描述

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

解题思路

嗯,这题就是上一题(51.N皇后)的翻版,上一题要求输出所有解法,这一题却只要求数量就行了。
所以。。。当然是选择在51题的基础上套一层皮啦(滑稽)
51题解法参照:
51.N皇后(N-Queens)

实现代码

class Solution {
    public int totalNQueens(int n) {
        boolean[] l = new boolean[n];
        boolean[] x1 = new boolean[2*n-1];
        boolean[] x2 = new boolean[2*n-1];
        
        List<List<String>> list = new ArrayList();
        List<String> tmp = new ArrayList();
        
        if(n==0)    return 0;
        
        find(list, tmp, n, l, x1, x2);
        
        return list.size();
    }
    
    public static void find(List<List<String>> list, List<String> tmpList, int n, boolean[] l, boolean[] x1, boolean[] x2){
        if(tmpList.size()==n){
            list.add(new ArrayList<>(tmpList));
            return;
        }
        int i = tmpList.size();
        for(int j=0;j<n;j++){
            if(l[j]==false && x1[j+i]==false && x2[n-1+i-j]==false){
                tmpList.add(append(j, n));
                l[j]=true;
                x1[j+i]=true;
                x2[n-1+i-j]=true;
                find(list, tmpList, n, l, x1, x2);
                l[j]=false;
                x1[j+i]=false;
                x2[n-1+i-j]=false;
                tmpList.remove(tmpList.size()-1);
            }
        }

    }
    
    public static void println(List<String> list){
        for(int i=0;i<list.size();i++)
            System.out.print(list.get(i)+" ");
        System.out.println();
        return;
    }
    
    public static String append(int ind, int n){
        StringBuilder res = new StringBuilder("");
        for(int i=0;i<ind;i++){
            res.append(".");
        }
        res.append("Q");
        for(int i=ind+1;i<n;i++){
            res.append(".");
        }
        return res.toString();
    }
}
IEEE Access 上岸指南,附含泪整理的 cover letter 、沟通邮件、终版文档等资料包 终于上岸了! 我是一个小硕,本科期间发表过两篇水文,奈何学校有更高的毕业要求,只能硬着头皮尝试一下 SCI。 想投 IEEE Access 的朋友都应该知道 小木虫论坛 对这个期刊的讨论,褒贬不一,有的人说是大水刊,有的人说有难度。 比如: @wow_: 不可否认,灌水期刊。只要之前中过一篇,再投基本没有不录用的!我们实验室其他老师说过一区除外的收费期刊都应该禁止灌水。 @pssp: 审稿人还... 阅读详情

相关推荐

Ubuntu20.04系统Cuckoo sandbox所需环境搭建及安装(超详细图文)

请勿叫我大神,我只是互联网的搬运工~ 前言 本教程以Ubuntu20桌面版作为示范,服务器版同样适用,但可能稍微麻烦一点,服务器版本的话安装Xmanage套装使用可能会相对轻松一些,由于后面会使用到vbox的使用,对vbox命令行操作不熟悉的小伙伴用xmanage可能会相对轻松一点。 提示:以下是本篇文章正文内容,下面案例可供参考 安装ubuntu20桌面版 步骤1:转到https://ubuntu.com/download/desktop下载下载.iso。 步骤2:使用您选择的虚拟机监控程序(VMWa

ElsonHY的博客 1万+

Leetcode 52. N-Queens II N皇后 II

题目:n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。上图为 8 皇后问题的一种解法。给定一个整数 n,返回 n 皇后不同的解决方案的数量。解题思路:和Leetcode 51. N-Queens N皇后一样,都是用回溯法解决,相较于上一题的输出棋盘,这题输出合法棋盘总和相对更简单一点。空间复杂度O(n)。代码实现:class Solution { ...

zhangzhetaojj的博客 787

Vue集成飞书前端JSSDK

文章目录前言<1>飞书前端JSSDK<2>使用步骤1.将JSSDK引入到VUE2.读入数据总结 前言 公司需要使用飞书软件,所以转战飞书开发,也是对新知识的探索与研究,飞书SDK也一直都在更新,路虽远,行必达。 <1>飞书前端JSSDK 1、官网地址:https://open.feishu.cn/document/uYjL24iN/uITO4IjLykDOy4iM5gjM 2、当前使用的飞书前端JSSDk的版本:1.5.4 <!-- 在html文档中 --&gt

A 1万+

LeetCode 52. N皇后 II(N-Queens II)

LeetCode.jpg 52. N皇后 II N皇后 II n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。 image.png 上图为 8 皇后问题的一种解法。 给定一个整数 n,返回 n 皇后不同的解决方案的数量。 示例: 输入: 4 输出: 2 解释: ...

墨1024 526

物料帐配置之 重估消耗

物料帐配置 ML material ledger

SAP刺客的博客 5937

国产Flash替代方案:手把手教你用XSCT烧写ZYNQ7045的BOOT.BIN(附完整命令解析)

本文详细介绍了国产Flash替代方案在ZYNQ7045上的应用,通过XSCT工具链实现BOOT.BIN的精准烧写。内容涵盖国产Flash兼容性检查、PetaLinux环境搭建、XSCT烧写全流程及故障排查,帮助开发者高效完成国产化替代,提升硬件开发效率。

weixin_33670786的博客 436

52. N-Queens II N皇后II

网址:https://leetcode.com/problems/n-queens-ii/ 方法1:按照逻辑思路,通过回溯法解决问题。速度较慢! class Solution { public: void backTracking(vector<string> res, int &ans, int r, int n) { bool...

weixin_33890499的博客 68

Minitab田口设计实战:如何用正交试验优化遗传算法参数(附完整操作步骤)

本文详细介绍了如何利用Minitab田口设计进行遗传算法参数优化,通过正交试验方法显著提升效率。文章涵盖实验设计、Minitab操作步骤、结果分析及高级技巧,帮助工程师快速掌握这一工业级优化技术,实现算法性能的显著提升。

wind6的博客 877

Leetcode 52 N-Queens II N皇后问题

题目: Then-queens puzzle is the problem of placingnqueens on ann×nchessboard such that no two queens attack each other. Given an integern, return the number ofdistinct solutions to then-queen...

Lin_QC的博客 1254

三极管和MOS管工作原理详解

PN结的形成 PN结是三极管以及场效应管中最基本的组成部分,要想彻底搞明白三极管以及场效应管的工作原理,必须先搞清楚PN结形成的原理和工作特性。 本征半导体以及空穴对 本征半导体(intrinsic semiconductor))完全不含杂质且无晶格缺陷的纯净半导体称为本征半导体。主要常见代表有硅、锗这两种元素的单晶体结构。硅、锗都是4价原子,在半导体内部形成相对稳定的共价键结构,如图 1所

技术交流是便宜的的博客 10万+

14、利用Helm和GitOps实现Kubernetes资源管理与CI/CD流程优化

本文介绍了如何结合Helm、GitOps和Terraform等工具,优化Kubernetes资源管理和CI/CD流程。内容涵盖了Helm提供程序的配置、GitOps的核心理念、CI/CD管道的构建与测试策略、GitHub源代码管理模型以及流程优化建议,旨在提升软件开发和部署的效率与质量。

y7z8a9的博客 159

52.N-Queens II N皇后II

class Solution { public int sum = 0; public int totalNQueens(int n) { int[] arr = new int[n]; Nqueen(0, n, arr); return sum; } public void Nqueen(int i, i...

aoduanrou3097的博客 108

2023推免(夏令营+套实验室)面试总结(博文附问题汇总和参考答案)

2023推免(夏令营+套实验室)面试总结(博文附问题汇总和参考答案)

m0_51339444的博客 1819

Leetcode之回溯法专题-52. N皇后 II(N-Queens II)

Leetcode之回溯法专题-52. N皇后 II(N-Queens II) 与51题的代码80%一样,只不过52要求解的数量,51求具体解,点击进入51 class Solution { int ans = 0; public int totalNQueens(int n) { char mp[][] = new char...

denghan1065的博客 156

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

LeetCode:52. N-Queens(N 皇后问题) II - Python

52. N皇后 II 问题描述: n皇后问题研究的是如何将n个皇后放置在n×n的棋盘上,并且使皇后彼此之间不能相互攻击。 上图为 8 皇后问题的一种解法。 给定一个整数n,返回 n 皇后不同的解决方案的数量。 示例: 输入: 4 输出: 2 解释: 4 皇后问题存在如下两个不同的解法。 [ [&amp;amp;quot;.Q…&amp;amp;quot;, // 解法 1 “…Q”, “Q…”, “…Q.”], [&amp;amp;quot;…Q.&amp;amp;

Growth Diary 906

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

【LeetCode 面试经典150题】52. N-Queens II N皇后问题 II

n。

qq_43513394的博客 448

LeetCode 52. N 皇后 II(N-Queens II)题解

N皇后II问题要求计算在n×n棋盘上放置n个互不攻击的皇后的不同解法数量。采用回溯算法逐行放置皇后,检查列和对角线冲突,使用数组记录皇后位置。当完成所有行放置时计数加一。该算法时间复杂度为O(n!),空间复杂度O(n)。对于n≤9的输入,普通回溯即可高效解决;对于更大的n可采用位运算优化。示例中n=4时有2种解法,n=1时有1种解法。

2302_80441878的博客 296

52. N-Queens II(N-皇后II)

题目链接:https://leetcode.com/problems/n-queens-ii/ 这道题比51题还要简单些,直接在上题代码上修改了一些。 AC 4ms Java: class Solution { private int ans=0; public int totalNQueens(int n) { String[][] strs=new St...

God_Mood的博客 150

51. N-Queens && 52. N-Queens II(N皇后)

51. N-Queens 经典的N皇后问题,典型的回溯问题,这里我就不解释什么思路了,我相信大家对于N皇后问题还是非常熟悉的,直接上代码。 class Solution { public: vector<vector<string>> solveNQueens(int n) { vector<vector<string>> res; ve...

asd994144293的博客 249

【LeetCode】#52N皇后II(N-Queens II)

【LeetCode】N皇后II(N-Queens II) 题目描述 n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。 给定一个整数 n,返回 n 皇后不同的解决方案的数量。 示例 输入: 4 输出: 2 解释: 4 皇后问题存在如下两个不同的解法。 [ [&quot;.Q…&quot;, // 解法 1 “…Q”, “Q…”, “…Q.”], [&quot;…Q.&quot;, // ...

weixin_43858604的博客 124

[LeetCode] 52. N-Queens II N皇后问题之二

Then-queens puzzle is the problem of placingnqueens on ann×nchessboard such that no two queens attack each other. Given an integern, return the number ofdistinct solutions to then-queens ...

weixin_30399055的博客 135

【LeetCode】 52. N-Queens II N皇后 II(Hard)(JAVA)

【LeetCode】 52. N-Queens II N皇后 II(Hard)(JAVA) 题目地址: https://leetcode-cn.com/problems/n-queens/ 题目描述: The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens...

qq_16927853的博客 194

leetcode 52. N-Queens II(N皇后II)

nxn的棋盘上要放n个皇后,皇后不能在同一行,同一列,两条对角线上。 因为皇后能横着走,竖着走,还能沿两个方向的对角线斜着走。思路: 回溯。 保证不冲突即可,用boolean数组代表列,对角线,反对角线上有无冲突。......

蓝羽飞鸟的博客 207

LeetCode 52. N-Queens II(N皇后)

原题网址:https://leetcode.com/problems/n-queens-ii/ Follow up for N-Queens problem. Now, instead outputting board configurations, return the total number of distinct solutions. 方法一:深度优先搜索,使用一

James Pan 1063

leetCode 52.N-Queens II (n皇后问题II) 解题思路和方法

N-Queens II Follow up for N-Queens problem. Now, instead outputting board configurations, return the total number of distinct solutions. 思路:解决了上题,这题也就迎刃而解,或者说这题要不上题还要简单一些。 具体代码如下: pub

Android进阶 2807

【leetcode】52. N皇后 II(n-queens-ii)(回溯)[困难]

链接 https://leetcode-cn.com/problems/n-queens-ii/ 耗时 解题:35 min 题解:7 min 题意 n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。 思路 根据题意,每行每列只能放一个。所以 dfs 每行,找每 行 可以放的 列,对于每一列所确定的位置,都检查当前位置是否安全(横竖斜都不在攻击范围内),如果安全则选定这个位置,dfs 下一行,直到 dfs 到第 n 行,说明当前的放法就可行,结果+1。 时间复杂度

Krone_的博客 256
上一篇: 51.N皇后(N-Queens)
下一篇: 55.跳跃游戏(Jump Game)
將晨
博客等级 码龄10年 33粉丝 30原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值