美文网首页
LeetCode每日一题:n queens ii

LeetCode每日一题:n queens ii

作者: yoshino | 来源:发表于2017-06-14 15:46 被阅读21次

问题描述

Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.

问题分析

和上一题类似,只是输出改成了结果数量,其实比上一题简单。

代码实现

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

    public int totalNQueens(int n) {
        ArrayList<Integer> res = new ArrayList<Integer>();
        res.add(0);
        helper2(n, 0, new int[n], res);
        return res.get(0);
    }

    private void helper2(int n, int row, int[] columnForRow, ArrayList<Integer> res) {
        if (row == n) {
            res.set(0, res.get(0) + 1);
            return;
        }
        for (int i = 0; i < n; i++) {
            columnForRow[row] = i;
            if (check(row, columnForRow)) {
                helper2(n, row + 1, columnForRow, res);
            }
        }
    }

相关文章

网友评论

      本文标题:LeetCode每日一题:n queens ii

      本文链接:https://www.haomeiwen.com/subject/nuzsqxtx.html