• 19.2.8 [LeetCode 52] N-Queens II


    The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

    Given an integer n, return the number of distinct solutions to the n-queens puzzle.

    Example:

    Input: 4
    Output: 2
    Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
    [
     [".Q..",  // Solution 1
      "...Q",
      "Q...",
      "..Q."],
    
     ["..Q.",  // Solution 2
      "Q...",
      "...Q",
      ".Q.."]
    ]
     1 class Solution {
     2 public:
     3     bool valid(vector<int>&a, int x, int y) {
     4         for (int i = 0; i < x; i++)
     5             if (y == a[i] || abs(a[i] - y) == x - i)
     6                 return false;
     7         return true;
     8     }
     9     void build(int&ans,vector<int>&now,int row) {
    10         int n = now.size();
    11         if (row == n) 
    12             ans++;
    13         else {
    14             for (int i = 0; i < n; i++)
    15                 if (valid(now, row, i)) {
    16                     now[row] = i;
    17                     build(ans, now, row + 1);
    18                 }
    19         }
    20     }
    21     int totalNQueens(int n) {
    22         vector<int>now(n, -1);
    23         int ans = 0;
    24         build(ans, now, 0);
    25         return ans;
    26     }
    27 };
    View Code

    用&传送参数可以快好多,终于知道上一题为什么比别人慢了

  • 相关阅读:
    IO流
    java的反射机制
    docker下安装mysql
    makefile
    python轻量级orm
    MySQLdb与sqlalchemy的简单封装
    python网络socket编程
    解决mysqldb查询大量数据导致内存使用过高的问题
    sqlalchemy根据数据库结构生成映射的实体
    centos7构建python2.7常用开发环境
  • 原文地址:https://www.cnblogs.com/yalphait/p/10356335.html
Copyright © 2020-2023  润新知