Leetcode - N-Queens II

My code:

public class Solution {
    private int counter = 0;
    public int totalNQueens(int n) {
        if (n <= 0) {
            return 0;
        }
        
        helper(0, new boolean[n], new boolean[2 * n], new boolean[2 * n], n);
        return counter;
    }
    
    private void helper(int row, boolean[] col, boolean[] l1, boolean[] l2, int n) {
        if (row >= n) {
            counter++;
            return;
        }
        for (int i = 0; i < n; i++) {
            int index1 = row - i + n;
            int index2 = 2 * n - i - row - 1;
            if (!col[i] && !l1[index1] && !l2[index2]) {
                col[i] = true;
                l1[index1] = true;
                l2[index2] = true;
                helper(row + 1, col, l1, l2, n);
                col[i] = false;
                l1[index1] = false;
                l2[index2] = false;
            }
        }
    }
}

就把 I 改了下,就交了。思路差不多。
核心就是,那两条对称斜线,是可以各用一个数字来表示的。

Anyway, Good luck, Richardo! — 09/23/2016

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/85c7578c9cc9#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞