zoukankan      html  css  js  c++  java
  • 【LeetCode】52. N-Queens II

    N-Queens II

    Follow up for N-Queens problem.

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

    简单的回溯法。

    cur[i] == j 代表第i行的皇后位于第j列。

    对于每一行,尝试所有列,

    如果当前行尝试的位置不与前面所有行的位置冲突,则可以递归到下一行。

    class Solution {
    public:
        int totalNQueens(int n) {
            int count = 0;
            vector<int> cur;
            Helper(count, cur, 0, n);
            return count;
        }
        void Helper(int& count, vector<int> cur, int pos, int n)
        {
            if(pos == n)
                count ++;
            else
            {
                for(int i = 0; i < n; i ++)
                {
                    cur.push_back(i);
                    if(check(cur))
                        Helper(count, cur, pos+1, n);
                    cur.pop_back();
                }
            }
        }
        bool check(vector<int> cur)
        {
            int size = cur.size();
            int loc = cur[size-1];
            for(int i = 0; i < size-1; i ++)
            {
                //never same row
                
                //col
                if(cur[i] == loc)
                    return false;
                
                //diag
                if(abs(cur[i]-loc) == abs(i-size+1))
                    return false;
            }
            return true;
        }
    };

  • 相关阅读:
    new、delete和malloc、free
    重写与重载
    面向对象三个基本特征
    Js零散知识点笔记
    ES6 笔记
    js 单例模式笔记
    关于闭包的见解
    DOM笔记
    浏览器差异
    JS高级程序设计 笔记
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4159225.html
Copyright © 2011-2022 走看看