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

    Follow up for N-Queens problem.

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

    思路:和 N-queens 一样,不过只统计个数而言,更加简单了

    class Solution {
        vector<int> x;
        int m_res;
    
        bool checkTwoPoints(int i, int j, int xi, int xj)
        {
            //cout << "check i	" << i << endl;
            //cout << "check j	" << j << endl;
            if(xi == xj) // same column
                return false;
            if( abs(xi-xj) == abs(i-j)) // diag
                return false;
            return true;
        }
    
        bool check(vector<int> x, int n) // check x[n] and x[0 .. n-1]
        {
            for(int i = 0; i < n; i++)
            {
                if(!checkTwoPoints(i, n, x[i], x[n]))
                    return false;
            }
            return true;
        }
    
        void dfs(int n)
        {
            if(n == x.size() )
            {   
                //printVector(x);
        
                m_res ++; 
                return;
            }   
    
            for(int i = 0; i < x.size(); i++)
            {
                x[n] = i;
    
                // check if x[n] is available
                if(check(x, n))
                    dfs(n+1);
            }
    
        }
        public:
        int totalNQueens(int n)
        {
            x.resize(n);
            m_res = 0;
    
            dfs(0);
            return m_res;
        }
    };
  • 相关阅读:
    单机部署Fastfds+nginx
    day_ha配置文件
    day_1_登录接口

    表(list)
    Java基础01 ------ 从HelloWorld到面向对象
    测试V模型
    360极速模式和兼容模式区别
    初识VBS
    Bug描述规范
  • 原文地址:https://www.cnblogs.com/diegodu/p/4313778.html
Copyright © 2011-2022 走看看