首页 > 其他 > 详细

LeetCode "N-Queens II"

时间:2014-07-21 11:08:08      阅读:350      评论:0      收藏:0      [点我收藏+]

Classic recursion\pruning problem. We can use O(n) space: A[i] = j means [i,j] is occupied.

bubuko.com,布布扣
class Solution {
public:
    int ret;
    bool isValid(int *A, int r)
    {
        for (int i = 0; i < r; i++)
            if ((abs(A[i] - A[r]) == abs(i - r) ||    A[i] == A[r]))
                return false;
        return true;
    }

    void go(int *A, int r, int n)
    {
        if (r == n)
        {
            ret++;
            return;
        }
        for (int i = 0; i < n; i++)
        {
            A[r] = i;
            if (isValid(A, r))    go(A, r + 1, n);
        }
    }
    int totalNQueens(int n) {
        ret = 0;
        int *A = new int[n];

        go(A, 0, n);

        delete[] A;
        return ret;
    }
};
View Code

LeetCode "N-Queens II",布布扣,bubuko.com

LeetCode "N-Queens II"

原文:http://www.cnblogs.com/tonix/p/3857663.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!