zoukankan      html  css  js  c++  java
  • 【Lintcode】033.N-Queens II

    题目:

    Follow up for N-Queens problem.

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

    Example

    For n=4, there are 2 distinct solutions.

    题解:

    Solution 1 ()

    class Solution {
    public:
        void dfs(int &res, int n, vector<int>& pos, int row) {
             if(row >= n) {
                 ++res;
                 return;
             }
             for(int col=0; col<n; ++col) {
                if (!isValid(pos, row, col)) {
                    continue;
                }
                pos[row] = col;
                dfs(res, n, pos, row + 1);
                pos[row] = -1;
             }
        }
        bool isValid(vector<int>& pos, int row, int col) {
            for (int i = 0; i < row; ++i) {
                if (pos[i] == col || abs(row - i) == abs(col - pos[i])) {
                    return false; 
                }
            }
            return true;
        }
        int totalNQueens(int n) {
            int res = 0;
            vector<int> pos(n, -1);
            dfs(res, n, pos, 0);
            return res;        
        }
    };
  • 相关阅读:
    FILTER(过滤器)
    HDFS优缺点
    python运算符
    python变量类型
    python变量存储
    python编码问题
    【一:定义】python 简介
    如何学一门新技术
    Django安装
    redis 安装及启动关闭
  • 原文地址:https://www.cnblogs.com/Atanisi/p/6863683.html
Copyright © 2011-2022 走看看