本文主要是介绍leetcode-52. N-Queens II,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
leetcode-52. N-Queens II
题目:
>
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
跟上一题一样,比上一题简单。51-N-Queens I
public class Solution {private int ret = 0;public int totalNQueens(int n) {boolean [][] mat = new boolean[n][n];helper(mat,0);return ret;}private void helper( boolean[][] mat,int len){if(len==mat.length){ret++;return ;}for(int i=0;i<mat.length;i++){if(verify(mat,len,i)){mat[len][i] = true;helper(mat,len+1);mat[len][i] = false;}}}private boolean verify(boolean[][] mat, int ni , int nj){for(int i = 0 ; i<ni ; i++){if(mat[i][nj]) return false;if(ni-i-1>=0 && nj-i-1>=0 && mat[ni-i-1][nj-i-1]) return false;if(ni-i-1>=0 && nj+i+1<mat.length && mat[ni-i-1][nj+i+1]) return false;}return true;}
}
这篇关于leetcode-52. N-Queens II的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!