• 【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;        
        }
    };
  • 相关阅读:
    @hdu
    @51nod
    @51nod
    @51nod
    JS-正则表达式常规运用
    CSS-复选框默认样式修改
    Vue-路由传参query与params
    Vue-阻止页面回退
    Vue-表单提交
    JS-原生的ajax
  • 原文地址:https://www.cnblogs.com/Atanisi/p/6863683.html
Copyright © 2020-2023  润新知