[LeetCode] N-Queens II

If you have solved the N-Queens problem, this one can be solved in a similar manner. Starting from the first row, we try each of its columns. If there is no attack, we move on to the next row based previous rows. Otherwise, we backtrack to the current row and try another selection of column position. Once we meet the last row, increase the counts by 1.

The code is as follows.

 1 class Solution {
 2 public:
 3     int totalNQueens(int n) {
 4         int* colPos = new int [n];
 5         int counts = 0;
 6         solve(colPos, n, 0, counts);
 7         delete colPos;
 8         return counts;
 9     }
10 private:
11     bool noAttack(int*& colPos, int row, int col) {
12         for (int r = row - 1, ld = col - 1, rd = col + 1; r >= 0; r--, ld--, rd++)
13             if (colPos[r] == col || colPos[r] == ld || colPos[r] == rd)
14                 return false;
15         return true;
16     }
17     void solve(int*& colPos, int n, int row, int& counts) {
18         if (row == n) {
19             counts++;
20             return;
21         }
22         for (int col = 0; col < n; col++) {
23             colPos[row] = col;
24             if (noAttack(colPos, row, col))
25                 solve(colPos, n, row + 1, counts);
26         }
27     }
28 };

Someone has even suggested a damn clever solution to this problem using bit-manipulations in this link (refer to the first answer).

I rewrite the code below for reference.

 1 class Solution {
 2 public:
 3     int totalNQueens(int n) {
 4         int counts = 0;
 5         int limit = (1 << n) - 1;
 6         solve(0, 0, 0, limit, counts);
 7         return counts;
 8     }
 9 private:
10     void solve(int hProj, int lProj, int rProj, int limit, int& counts) {
11         if (hProj == limit) {
12             counts++;
13             return;
14         }
15         int pos = limit & (~(hProj | lProj | rProj));
16         while (pos) {
17             int p = pos & (-pos);
18             pos ^= p;
19             solve(hProj | p, (lProj | p) >> 1, (rProj | p) << 1, limit, counts);
20         }
21     }
22 };
时间: 2024-12-28 01:21:32

[LeetCode] N-Queens II的相关文章

LeetCode:N-Queens I II(n皇后问题)

N-Queens The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. Each solution contains a distinct board configur

LeetCode --- 90. Subsets II

题目链接:Subsets II Given a collection of integers that might contain duplicates, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example, If S = [1,2,2]

【leetcode】N-queens II

问题: 返回N皇后问题解的个数. 分析: 详见 N-queens 实现: bool nextPermutation(vector<int> &num) { int i = num.size() - 1; while (i >= 1) { if(num[i] > num[i - 1]) { --i; int ii = num.size() - 1; while (ii > i && num[ii] <= num[i]) --ii; if(ii &g

leetcode: Subsets &amp; Subsets II

SubsetsGiven a set of distinct integers, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example,If S = [1,2,3], a solution is: [ [3], [1], [2], [1,2

[LeetCode] Jump Game II(贪婪算法)

Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps

leetCode: Single Number II [137]

[题目] Given an array of integers, every element appears three times except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? [题意] 给定一个整数以外,其中除了一个整数只出现一次以外,其他

LeetCode: Jump Game II [044]

Perface 如果让你实现这个页面和一些操作的,比如点击1.2.3等就在那个input text中显示,还有删除功能,拨打我们先不要管它,只是模拟而已.要是我刚开始做的话,我会这样做: 用css.HTML布局那个界面 用javascript的事件委托监听那个按钮的父节点的点击事件 但是如果我想用面向对象的思想做呢?我是用Ext做的,所以我想说的是它帮我封装了很多.可能一些没用过Ext的人不太了解我下面贴的代码,但是我会尽量解释清楚的! Description ContactTelPanel =

LeetCode: Combination Sum II [039]

[题目] Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. Each number in C may only be used once in the combination. Note: All numbers (including target) will be

8.18 [LeetCode 52] N-Queens II

[LeetCode 52] N-Queens II | COMMENTS Question link Follow up for N-Queens problem. Now, instead outputting board configurations, return the total number of distinct solutions. Stats Frequency 3 Difficulty 4 Adjusted Difficulty 2 Time to use ——– Ratin

LeetCode——Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example: Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ / 7 2 5 1 return [ [5,4,11,2], [5,8,4,5] ] 给定一个二叉树和一个值,找出所有根到叶的路径和等于