本文主要是介绍Leetcode204: N-Queens II,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
class Solution {
private:int num=0;
public: int isValid(int *a, int n, int row, int col) { int tmpcol=0; for(int tmprow=0;tmprow<row;tmprow++) { tmpcol = a[tmprow]; if(tmpcol == col)// 同列 return 0; if((tmpcol-col) == (tmprow - row))// 在同一右斜线 return 0; if((tmpcol-col) == (row - tmprow))// 在同一左斜线 return 0; } return 1; } void n_queens(int *a,int n, int index) { for(int i=0;i<n;i++) { if(isValid(a,n,index,i)) { a[index]=i; if(index == n-1) { num++; a[index]=0; return; } n_queens(a,n,index+1); a[index]=0; } } }
public:int totalNQueens(int n) {int *a = new int[n]; memset(a,0,sizeof(int)*n); n_queens(a,n,0); return num;}
};
这篇关于Leetcode204: N-Queens II的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!