首页 > 其他分享 >[LeetCode]N-Queens II

[LeetCode]N-Queens II

时间:2023-02-02 15:36:24浏览次数:45  
标签:return int II nqueens step ans LeetCode Queens


Question
Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

本题难度Hard。

【思路】
​N-Queens​​中返回棋盘变成了解的个数。不必多说。

【代码】

public class Solution {
int ans=0;
public int totalNQueens(int n) {
//require
if(n<=0)
return ans;
//create
int[] nqueens=new int[n];
//invariant
dfs(nqueens,n,0);
//ensure
return ans;
}

private boolean isValid(int[] nqueens,int step){
for(int i=0;i<step;i++){
if(nqueens[i]==nqueens[step]||Math.abs(nqueens[i]-nqueens[step])==(step-i))
return false;
}
return true;
}

private void dfs(int[] nqueens,int n,int step){
//base case
if(step>n-1){
ans++;
return;
}

for(int i=0;i<n;i++){
nqueens[step]=i;
if(isValid(nqueens,step))
dfs(nqueens,n,step+1);
}

}
}

参考

​​N-Queens​​


标签:return,int,II,nqueens,step,ans,LeetCode,Queens
From: https://blog.51cto.com/u_9208248/6033692

相关文章

  • [LeetCode]Group Anagrams
    QuestionGivenanarrayofstrings,groupanagramstogether.Forexample,given:[“eat”,“tea”,“tan”,“ate”,“nat”,“bat”],Return:[[“ate”,“......
  • [LeetCode]Jump Game II
    QuestionGivenanarrayofnon-negativeintegers,youareinitiallypositionedatthefirstindexofthearray.Eachelementinthearrayrepresentsyourmaximu......
  • [LeetCode]Rotate Image
    QuestionYouaregivenannxn2Dmatrixrepresentinganimage.Rotatetheimageby90degrees(clockwise).Followup:Couldyoudothisin-place?本题难度Mediu......
  • mat 和IPIImage之间的转换
    Mat::operatorIplImageCreatestheIplImageheaderforthematrix.C++:Mat::operatorIplImage()constTheoperatorcreates theIplImageheaderforthematrixwi......
  • LeetCode 1143_ 最长公共子序列
    LeetCode1143:最长公共子序列题目给定两个字符串text1和text2,返回这两个字符串的最长公共子序列的长度。如果不存在公共子序列,返回0。一个字符串的子序列......
  • Consecutive sum II 1977
    ​​点击这里看题目链接ConsecutivesumII​​#include<stdio.h>#include<math.h>intmain(){unsignedlonglongm,n;scanf("%I64d",&n);while(n--){scan......
  • 【DFS】LeetCode 124. 二叉树中的最大路径和
    题目链接124.二叉树中的最大路径和思路一个子树内部的最大路径和=左子树提供的最大路径和+根节点值+右子树提供的最大路径和。即dfs(root.left)+root.val+dfs(r......
  • LeetCode - 709. To Lower Case
    题目ImplementfunctionToLowerCase()thathasastringparameterstr,andreturnsthesamestringinlowercase.Example1:Input:"Hello"Output:"hello"Example2:......
  • LeetCode - 344. Reverse String
    题目Writeafunctionthatreversesastring.Theinputstringisgivenasanarrayofcharacterschar[].Donotallocateextraspaceforanotherarray,youmust......
  • LeetCode - 771. Jewels and Stones
    题目You’regivenstrings​​J​​​representingthetypesofstonesthatarejewels,and​​S​​representingthestonesyouhave.EachcharacterinSisa......