Leetcode 51. N-Queens

Leetcode 51.N皇后N-Queens Leetcode 51.N皇后N-Queens题目描述(困难)示例题解题意理解:解题思路:备注 题目描述(困难) n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。 上图为 8 皇后问题的一种解法。 给定一个整数 n,返回所有不同的 n 皇后问题的解决方案。 每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 ‘Q’ 和 ‘.’ 分别代表... 阅读详情

51. N-Queens

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
题目链接:https://leetcode.com/problems/n-queens/description/
题目大意:n皇后问题,在n * n的棋盘上,摆放n个皇后,是同行同列以及两条同斜边不同时出现两个皇后。列出所有方案。
解题思路:裸dfs摆放皇后位置。
代码如下:
class Solution {
private:
    vector<vector<string> > ans;
    char a[1000][1000]; //表示棋盘
    int vis[10000];  //判断列是否重复
public:
    bool ok(int n,int x,int y){  //判断斜边上没有其他皇后(左斜上、左斜下、右斜上、右斜下四个方向遍历)
        for(int i = x + 1,j = y + 1;i < n && j < n ; i ++,j++ ){
            if(a[i][j] == 'Q')
                return false;
        }
        for(int i = x - 1,j = y - 1;i >= 0 && j >= 0 ;i -- ,j --){
            if(a[i][j] == 'Q')
                return false;
        }
        for(int i = x + 1,j = y - 1;i < n && j >=0 ;i ++ ,j --){
            if(a[i][j] == 'Q')
                return false;
        }
        for(int i = x - 1,j  = y + 1;i >= 0 && j < n;i --,j ++){
            if(a[i][j] == 'Q')
                return false;
        }
        return true;
    }
    void dfs(int n,int x){
        if(x == n){   如果皇后以摆放完,把棋盘数组转换成字符串数组押入答案数组
            vector<string> vt;
            for(int i = 0;i < n;i ++){
                string ns = "";
                for(int j = 0;j < n ;j ++){
                    ns += a[i][j];
                }
                vt.push_back(ns);
            }
            ans.push_back(vt);
            return ;
        }
        for(int i = 0;i < n;i ++){
            if(vis[i] || !ok(n,x,i))
                continue;
            a[x][i] = 'Q';
            vis[i] = 1;
            dfs(n, x + 1);
            vis[i] = 0;
            a[x][i] = '.';
        }
    }
    vector<vector<string> > solveNQueens(int n) {
        for(int i = 0;i < n; i ++){
            for(int j = 0;j < n;j ++){
                a[i][j] = '.';
            }
        }
        dfs(n,0);
        return ans;
    }
};



Ta-Lib源码解析(三):蜡烛图指标 (Candlestick Indicator) #(附Python重构代码和示意图)(补充中) 蜡烛图指标为识别K线形态的指标,笔者认为重点在于定义方式所提供的思路,背后的投资逻辑可以借鉴但不建议直接参考文档的翻译内容和源码逻辑存在不一致的现象,笔者分别列出中文百科中的定义和源码实际逻辑,供大家参考技术分析理论中的一些模糊词,ta-lib中给出了精确的定义源码 阅读详情

相关推荐

postman响应体:“msg“: “请求缺失签名Sign“、 “msg“: “请求缺失时间戳“

请求标头有Sign、Timestamp,但是直接将网址复制到postman时,Headers没有自动生成这两个参数,所以运行时会报错。

m0_46862648的博客 1706

Leetcode 51. N-Queens (python+cpp)

Leetcode 51. N-Queens题目解析 题目 解析 这道题本质上和79 word search是一样的。同样是修改状态矩阵来进行回溯,只不过进行recursion的每一步需要对行,列以及两条对角线分别进行检查。我们可以通过遍历行,对列进行recursion,或者是遍历列,对行进行recursion都可以。所以需要的状态矩阵就是行或列状态矩阵,以及两个对角线状态矩阵。 关键的一点是对与...

qq_37821701的博客 335

2021-03-08 使用SPDK部署NVMe over TCP

NVMe-oF Target入门指南 SPDK NVMe over Fabrics Target是一个用户空间应用程序,通过以太网,Infiniband或光纤通道等结构呈现块设备,SPDK目前支持RDMA和TCP传输。 本文将在已经编译好SPDK的基础上演示如何使用SPDK搭建NVMe over TCP,前提是您已经将一块NVMe硬盘挂载到linux系统中。 如果您想获取有关SPDK更详细的信息,请参考 官方文档。 演示过程的Host主机的ip地址是192.168.0.21,Target主机的ip地址是19

Pancras的博客 2843

LeetCode 51. N-Queens

题意求出含有nn个皇后的所有的棋盘摆放方案思路经典的DFSDFS + 回溯问题,使用loc[i]loc[i]表示第ii列的皇后在第几行,后面的就是DFS+回溯DFS + 回溯了,各大算法和数据结构的书中都有这种问题,就不再写思路了.代码class Solution { public: vector<vector<string>> solveNQueens(int n) { v

滴水穿石,慢慢积累,总会有成果 447

华为2022数字芯片笔试题

单选 1、ASIC开发流程中,如下环节的先后顺序是? A. RTL-> Synthesis->P&R B. Synthesis->P&R->RTL C. Synthesis->RTL->P&R D.RTL->P&R->Synthesis 2、o10换算成十进制是多少? A. 8 B.16 C.10 D.2 3、reg [7:0] mem [1:256];initial $readmemh("me..

weixin_44072819的博客 1万+

SAP 接口测试操作-业务顾问

业务顾问测试接口操作

weixin_43657667的博客 5156

Leetcode 51 N Queens && Leetcode N Queens II

代表在第i行第j列放一个皇后。当数组满足长度要求时dfs结束。传入参数u表示当前我需要在第u行加入一个皇后,遍历所有n列,判断我皇后是否可以放入,如果可以放,那么就放,进入下一层dfs。,形成n*n的棋盘,棋盘上放n个皇后,确保皇后之间不会相互吃(皇后可以直线吃,斜线吃)题解:首先这是一道dfs,枚举所有可以放n皇后的地方。构造一个数组pos,

xxxmmc的博客 501

小米手机安装Burp证书失败原因与DER格式改造指南

CA证书是HTTPS抓包和移动安全测试的基础组件,其本质是遵循X.509标准的数字凭证,依赖ASN.1/DER编码格式与完整证书链实现可信验证。Android系统默认支持PEM和DER两种编码,但MIUI自14版本起强化安全策略,仅识别DER二进制格式,并强制校验Subject Alternative Name(SAN)、Basic Constraints及证书链完整性。这种企业级加固逻辑导致Burp Suite导出的PEM格式.cer文件在小米设备上‘安装成功但无效’。本文聚焦证书格式转换、SAN字段注入

weixin_33646989的博客 625

LeetCode-51-N-Queens 八皇后问题dfs

class Solution(object): N=0 P=[] ans=[] def solveNQueens(self, n): """ :type n: int :rtype: List[List[str]] """ self.N=n self.ans=[]

世靖的码场 949

在树莓派4B上基于NCNN框架部署YOLOv8的实战教程

摘要:本文详细介绍了在树莓派4B上基于NCNN框架部署YOLOv8目标检测模型的完整流程。从PyTorch模型转换为NCNN格式,到树莓派环境配置(OpenCV和NCNN编译),再到C++代码实现与优化,涵盖模型加载、推理和绘图等核心功能。测试结果显示,树莓派4B上可实现约2 FPS的检测速度,Windows平台达6~7 FPS。文章还提供了量化模型、多线程优化等实用建议,并附常见问题解答,为边缘设备部署轻量化目标检测提供了可行方案。(149字)

m0_64661770的博客 595

K8s(二十一):在 Kubernetes 集群中部署 MySQL8.0 高可用集群(1主2从)

🔴 K8s(二十一):在 Kubernetes 集群中部署 MySQL8.0 高可用集群(1主2从)

✨ 欢迎来到【Seal ^_^ 的优快云博客】!✨ 3万+

leetcode 51. N-Queens

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

PaladinDu的专栏 202

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

LeetCode 51 N-Queens

思路 dfs搜索,其实是排列型搜索permutation。利用一个List来存每一列上存了什么数字,索引就是行数,可以保证每一行只有一个数字。 搜索部分就是permutation模板实现,只是模板中的visit判断放入判断是否相互攻击的函数中了。 判断是否不会相互攻击:(1)每行只有一个:通过list索引自动解决 (2)每列只有一个:搜索所有已经存进list中的index是否与将加入的index重...

我要上岸的博客 210

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

leetcode 51. N-Queens 、52. N-Queens II

51. N-Queens 使用isValid判断当前的位置是否合法 每次遍历一行,使用queenCol记录之前行的存储位置,一方面是用于判断合法,另一方面可以根据存储结果输出最终的结果 棋盘的斜线都是45°的,所以两个位置x的差值和y的差值应该是相等的 class Solution { public: vector<vector<string> &...

weixin_30418341的博客 115

深度学习工具包 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")

LeetCode51——N-Queens

LeetCode51——N-Queens 求N皇后问题的所有解。 经典的算法,从大三刚开始学算法起到现在两年多了,一直不是掌握的很好。 这次借刷题,磕磕绊绊的解出来了。 思路: 1.定义一个check函数用来判断[row,col]这个位置是否能够防止一枚皇后Q,即检测横竖,对角线左右是否有皇后。 2.从0行0列开始往下递归放置Q,如果位置合适,则放置一枚Q,并继续向下一行进行递归防止。

上善若水 2049

LeetCode --- 51. N-Queens

题目链接:N-Queens The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens

makuiyu的专栏 2761

LeetCode //C - 51. N-Queens

【代码】LeetCode //C - 51. N-Queens。

Made in Code 1106

【LeetCode 51】 N-Queens

题目描述 The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. E...

iCode_girl的博客 140

Leetcode 51. N-Queens N皇后

Leetcode 51. N-Queens N皇后 标签: Leetcode 题目地址:https://leetcode-cn.com/problems/n-queens/ 题目描述 n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。 上图为 8 皇后问题的一种解法。 给定一个整数 n,返回所有不同的 n 皇...

CoderWangSon 259

[LeetCode 51] N-Queens

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

ExcitedZhang的博客 126

leetcode 51 N-Queens 回溯 万能结构

leetcode 51 N-Queens import java.util.ArrayList; import java.util.List; public class Solution { public static void main(String[] args){ Solution s = new Solution(); s.solveNQueens(4); }

独钓寒江雪 407
上一篇: Leetcode 55. Jump Game
下一篇: Leetcode 62. Unique Paths
雨狮子
博客等级 码龄12年 24粉丝 185原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值