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

    Follow up for N-Queens problem.

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

     1 public class Solution {
     2     int result = 0;
     3     public int totalNQueens(int n) {
     4         // Start typing your Java solution below
     5         // DO NOT write main() function
     6         result = 0;
     7         solve(new int[n], 0);
     8         return result;
     9     }
    10     public void solve(int[] arr, int pos){
    11         int size = arr.length;
    12         if(pos == size){
    13             result ++;
    14             return;
    15         }
    16         for(int i = 0; i < size; i ++)
    17             if(isValid(arr, pos, i)){
    18                 arr[pos] = i;
    19                 solve(arr, pos + 1);    
    20             } 
    21     }
    22     public boolean isValid(int[] arr, int pos, int check){
    23         for(int i = 0; i < pos; i ++)
    24             if(check == arr[i] || Math.abs(pos - i) == Math.abs(check - arr[i])) return false;
    25         return true;
    26     }
    27 }
  • 相关阅读:
    mongodb 配置单实例与双实例
    redis 集群 搭建
    memcached 搭建
    公网yum 源地址
    jdk 安装
    activemq 搭建--集群
    zookeeper 安装
    activemq 安装-单点
    rabbitmq 集群
    python——网络编程
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3510008.html
Copyright © 2011-2022 走看看