52 N皇后问题II

52 N皇后问题II_第1张图片
52 N皇后问题II_第2张图片

解法

这个题与51题基本一样,不同的地方在于,51题要输出具体的Q的位置排列,这个题只用输出数目,所以俺的思路就被带跑偏到动态规划了,但是尴尬的是,根本找不到n与n-1之间的关系,后面瞄了眼题解,发现和51题基本一样,还是回溯+剪枝,半个小时搞定,还算是比较可以了。

class Solution {


    private int count;

    public int totalNQueens(int n) {

        Set leftSlash = new HashSet<>();

        Set rightSlash = new HashSet<>();

        Set column = new HashSet<>();

        backTrack(0, n, leftSlash, rightSlash, column);

        return count;

    }

    private void backTrack(int row, int n, Set leftSlash, Set rightSlash, Set column) {

        // row等于n,说明所有行都有位置放元素

        if (row == n) {

            count++;

            return;

        }

        for (int j = 0; j < n; j++) {

            if (column.contains(j)) {

                continue;

            }

            int left = row + j;

            if (leftSlash.contains(left)) {

                continue;

            }

            int right = row - j;

            if (rightSlash.contains(right)) {

                continue;

            }

            column.add(j);

            leftSlash.add(left);

            rightSlash.add(right);

            backTrack(row + 1, n, leftSlash, rightSlash, column);

            column.remove(j);

            leftSlash.remove(left);

            rightSlash.remove(right);

        }

    }

}

你可能感兴趣的:(52 N皇后问题II)