[leetcode] 52. N-Queens II

这篇博客关注LeetCode的第52题,即N-Queens II问题。与第51题类似,但目标不是输出解决方案,而是计算不同解决方案的总数。该问题在算法领域被归类为Hard难度。
摘要由CSDN通过智能技术生成

Follow up for N-Queens problem.

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


这道题和第51题基本没有太大区别,题目难度为Hard。

如果需要详细解释请看第51题(传送门),具体代码:

class Solution {
public:
    int totalNQueens(int n) {
        vector<string> curRst(n, string(n, '.'));
        int cnt = 0;
        
        NQueens(curRst, 0, n, cnt);
        
        return cnt;
    }
    
    void NQueens(vector<string> &curRst, int row, int n, int &cnt) {
        if(row == n) {
            cnt++;
            return;
        }
        
        for(int i=0; i<n; i++) {
            bool flag = true;
            for(int j=0; j<row; j++) {
                if(curRst[j][i] == 'Q') {
                    flag = false;
                    break;
                }
                if((i+j-row >= 0) && (i+j-row <= n-1) && (curRst[j][i+j-row] == 'Q')) {
                    flag = false;
                    break;
                }
                if((i+row-j >= 0) && (i+row-j <= n-1) && (curRst[j][i+row-j] == 'Q')) {
                    flag = false;
                    break;
                }
            }
            
            if(flag) {
                curRst[row++][i] = 'Q';
                NQueens(curRst, row, n, cnt);
                curRst[--row][i] = '.';
            }
        }
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值