生活随笔
收集整理的這篇文章主要介紹了
LeetCode每日一题 52. N皇后 II
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接
思路
class Solution {
public:vector
<int> row
, col
;int totalNQueens(int n
) {int ret
= 0;row
.resize(n
, -1);col
.resize(n
, -1);ret
+= dfs(0, n
);return ret
;}int dfs(int x
, int n
) {if (x
== n
) return 1;int ret
= 0;for (int i
= 0; i
< n
; ++i
) {if (col
[i
] != -1) continue;bool flag
= true;for (int j
= 0; j
< n
; ++j
) {if (row
[j
] == -1) continue;if ((row
[j
]-i
== j
-x
) || (row
[j
]-i
== x
-j
)) {flag
= false;break;}}if (!flag
) continue;col
[i
] = x
;row
[x
] = i
;ret
+= dfs(x
+1, n
);col
[i
] = row
[x
] = -1;}return ret
;}
};
class Solution {
public:int totalNQueens(int n
) {int c
= 0, pie
= 0, na
= 0;int ret
= dfs(0, n
, c
, pie
, na
);return ret
;}int dfs(int r
, int n
, int c
, int pie
, int na
) {if (r
== n
) return 1;int ret
= 0;int bits
= (~(pie
|na
|c
)) & ((1<<n
) - 1);while (bits
> 0) {int p
= bits
& -bits
;ret
+= dfs(r
+1, n
, c
|p
, (pie
|p
)<<1, (na
|p
)>>1);bits
&= bits
- 1;}return ret
;}
};
與50位技術專家面對面20年技術見證,附贈技術全景圖
總結
以上是生活随笔為你收集整理的LeetCode每日一题 52. N皇后 II的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。