码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "N-Queens II"

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

标签:style   blog   http   color   os   io   

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"

标签:style   blog   http   color   os   io   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!