lintcode 中等题:N Queens II N皇后问题 II

题目:

根据n皇后问题,现在返回n皇后不同的解决方案的数量而不是具体的放置布局。

样例

比如n=4,存在2种解决方案

解题:

和上一题差不多,这里只是求数量,这个题目定义全局变量,递归的时候才能保存结果,参考程序

java程序:

class Solution {
    /**
     * Calculate the total number of distinct N-Queen solutions.
     * @param n: The number of queens.
     * @return: The total number of distinct solutions.
     */
    int result = 0;
    int[] cols;
    public int totalNQueens(int n) {
        //write your code here
        cols = new int [n];
        result = 0;
        DFS(n,0);
        return result;
    }
    
    public void DFS(int n,int row){
        if(n == row){
            result ++;
            return;
        }else{
            for(int i=0;i<n;i++){
                cols[row] = i;
                if(isValid(row))
                    DFS(n,row+1);
            }
        }
    }
    public boolean isValid(int row){
        for(int i=0;i<row;i++)
            if(cols[i]==cols[row] || Math.abs(cols[i]-cols[row])== row - i )
                return false;
        return true;
    }
};
View Code

总耗时: 1202 ms

原文地址:https://www.cnblogs.com/theskulls/p/4910026.html