zoukankan      html  css  js  c++  java
  • N-Queens II 解答

    Question

    Follow up for N-Queens problem.

    Now, instead outputting board configurations, return the total number of distinct solutions.

    Solution

    This problem seems like 2D DP, but it is not.

    For DP problem, usually we will have a/ some directions. But here, we can go to all four directions. So this can not be solved by DP.

    We still use the way to implement N-Queens.

    There is one stuff worth mentioning:

    In java, if in function f(x), we pass a variable x of primitive data type like int into a function g(x), the value of x in f(x) is not changed.

    If we want it to be modified, we need to pass a reference.

     1 public class Solution {
     2     
     3     public int totalNQueens(int n) {
     4         // Should use an object rather than a int variable here
     5         // We want "result" to be modified in helper function
     6         int[] result = {0};
     7         int[] queen = new int[n];
     8         helper(n, 0, queen, result);
     9         return result[0];
    10     }
    11     
    12     private void helper(int n, int rowNum, int[] queen, int[] result) {
    13         if (n == rowNum) {
    14             result[0]++;
    15             return;
    16         }
    17         
    18         for (int i = 0; i < n; i++) {
    19             queen[rowNum] = i;
    20             if (check(rowNum, queen))
    21                 helper(n, rowNum + 1, queen, result);
    22         }
    23     }
    24     
    25     private boolean check(int rowNum, int[] queen) {
    26         int colNum = queen[rowNum];
    27         for (int i = 0; i < rowNum; i++) {
    28             if ((colNum == queen[i]) || (queen[i] - i == colNum - rowNum) || (queen[i] + i == colNum + rowNum))
    29                 return false;
    30         }
    31         return true;
    32     }
    33 }
  • 相关阅读:
    数据汇总计算和分析的反思
    排名算法计算
    仿Spring读取配置文件实现方案
    xml 配置文件规范 校验
    批量插入数据(基于Mybatis的实现-Oracle)
    shallow copy 和 deep copy 的示例
    引用对象的使用和易产生bug的示例
    codis安装手册
    Redis安装手册
    map和list遍历基础
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4888816.html
Copyright © 2011-2022 走看看