陈中正的网络日志

LeetCode: N-Queens II

题目

https://oj.leetcode.com/problems/n-queens-ii/

分析

N-Queens这道题解法一样,略作修改即可。

代码

class Solution
{
public:
    int totalNQueens(int n)
    {
        vector<int> solution(n);
        helper(solution, 0, n);

        return res;
    }
    void helper(vector<int> &solution, int row, int n)
    {
        if (row == n)
            res++;
        else
        {
            for (int i = 0; i < n; i++)
            {
                if (isValid(solution, row, i))
                {
                    solution[row] = i;
                    helper(solution, row + 1, n);
                }
            }
        }
    }
    bool isValid(vector<int> &solution, int row, int col)
    {
        for (int i = 0; i < row; i ++)
            if (solution[i] == col || abs(i-row) == abs(solution[i]-col))
                return false;
        return true;
    }

private:
    int res = 0;
};

参考

http://blog.csdn.net/timberwolf_2012/article/details/40686105

本文章迁移自http://blog.csdn.net/timberwolf_2012/article/details/40711959

Categories:  OJ题解 

« LeetCode: Unique Paths LeetCode: N-Queens »