Leetcodes Solutions 52 N-Queens II

匯總

雪之下雪乃:leetcode解題總匯?

zhuanlan.zhihu.com圖標

Follow up for N-Queens problem.

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

思路1:

DFS

class Solution {public: int totalNQueens(int n) { vector<bool> col(n, true); vector<bool> anti(2*n-1, true); vector<bool> main(2*n-1, true); vector<int> row(n, 0); int count = 0; dfs(0, row, col, main, anti, count); return count; } void dfs(int i, vector<int> &row, vector<bool> &col, vector<bool>& main, vector<bool> &anti, int &count) { if (i == row.size()) { count++; return; } for (int j = 0; j < col.size(); j++) { if (col[j] && main[i+j] && anti[i+col.size()-1-j]) { row[i] = j; col[j] = main[i+j] = anti[i+col.size()-1-j] = false; dfs(i+1, row, col, main, anti, count); col[j] = main[i+j] = anti[i+col.size()-1-j] = true; } } }};

推薦閱讀:

二叉樹中和為某一值的路徑
數據科學家需要了解的5大聚類演算法
學點演算法之字元串的亂序檢查
038 Count and Say[E]
鏈表中倒數第k個節點

TAG:演算法 | 編程 | 數據結構 |