LeetCode:N-Queens II

N-Queens II




Total Accepted: 45401  Total Submissions: 114053  Difficulty: Hard

Follow up for N-Queens problem.

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

Subscribe to see which companies asked this question

Hide Tags
  Backtracking
Hide Similar Problems
  (H) N-Queens



























思路:

由于N个皇后的任意两个不能处在同一行,那么这肯定是每一个皇后占据一行。于是我们可以定义一个数组nums[N],数组中第i个数字表示位于第i行的皇后的列号。先把nums的N个数字分别用0~N-1初始化,接下来我们要做的事情就是对数组nums做全排列。由于我们是用不同的数字初始化数组中的数字,因此任意两个皇后肯定不同列。我们只需要判断得到的每一个排列对应的N个皇后是不是在同一对角斜线上,也就是数组的两个下标i和j,是不是i-j==nums[i]-nums[j]或者j-i==nums[i]-nums[j]。


因此实际上就是在(元重复元素)全排列(参考:LeetCode:Permutations)的基础上多了一个判断而已。


c++ code:

class Solution {
public:
    int totalNQueens(int n) {
        
        vector<int> nums(n);
        for(int i=0;i<n;i++)
            nums[i]=i;
        
        int count = 0;
        permute(nums, 0 ,count);
        return count;
    }
    
    
    // 自定义函数
    void permute(vector<int> &nums, int pos, int &count) {
        
        int n = nums.size();
        if(pos==n) {
            if(check(nums))
                count++;
            return;
        }
        for(int i=pos;i<n;i++) {
            swap(nums[pos], nums[i]);
            permute(nums, pos+1, count);
            swap(nums[i], nums[pos]);
        }
        
    }
    
    bool check(vector<int> &nums) {
        
        int n = nums.size();
        for(int i=0;i<n;i++) {
            for(int j=i+1;j<n;j++)
                // 判断是否在主、副对角线上
                if(i-j == nums[i]-nums[j] || j-i == nums[i]-nums[j])
                    return false;
        }
        return true;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值