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

    N-Queens II

    Follow up for N-Queens problem.

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

     
     1 class Solution {
     2 public:
     3     int totalNQueens(int n) {
     4         vector<int> q(n,-1);
     5         int result=0;
     6         getQueens(0,n,result,q);
     7         return result;
     8     }
     9    
    10     void getQueens(int level,int &n,int &result,vector<int> &q)
    11     {
    12         if(level==n)
    13         {
    14             result++;
    15             return;
    16         }
    17         bool flag=false;
    18         for(int i=0;i<n;i++)
    19         {
    20             q[level]=i;
    21             if(isValid(q,level))
    22             {
    23                 getQueens(level+1,n,result,q);
    24             }
    25             q[level]=-1;
    26         }
    27     }
    28    
    29    
    30     bool isValid(vector<int> &q,int &level)
    31     {
    32  
    33         for(int i=0;i<level;i++)
    34         {
    35             if(q[i]==q[level]||abs(q[level]-q[i])==abs(level-i)) return false;
    36         }
    37        
    38         return true;
    39     }
    40  
    41 };
  • 相关阅读:
    tornado之获取参数
    tornado中命名路由及反向解析使用
    options模块介绍
    服务的启动
    redis操作
    python中使用redis模块, 设置过期时间
    LaTeX
    word 摘要
    常用命令
    机器学习的建议
  • 原文地址:https://www.cnblogs.com/reachteam/p/4214001.html
Copyright © 2011-2022 走看看