leetcode52 N-Queens II
2016-03-06 19:42
447 查看
52. N-Queens II
Total Accepted:41407 Total Submissions:
107148 Difficulty: Hard
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
AC代码:
class Solution { public: int row[105]; //记录每一行皇后的位置 bool issafe(const int &i, const int &j, const int &n) { for (int k = 1; k < i; ++k) if (j == row[k] || abs(i - k) == abs(j - row[k])) return false; return true; } void findPos(const int &i, const int &n, int &ans) //i表示已经放置到第i行,j表示皇后在第i行放置于j { for (int j = 1; j <= n; ++j) { if (i > n) return; if (issafe(i, j, n)) //判断当前位置是否可以放皇后 { if (i == n) //皇后已放到最后一行,找到一种解法,ans + 1 { ++ans; continue; } row[i] = j; findPos(i + 1, n, ans); row[i] = 0; } } } int totalNQueens(int n) { if (1 == n) return 1; int ans = 0; memset(row, 0, sizeof(row)); for (int i = 1; i <= n; ++i) //在第一行依次放置皇后 { row[1] = i; findPos(2, n, ans); } return ans; } };
相关文章推荐
- (java)Unique Binary Search Trees
- POJ 3458 Colour Sequence
- hdu 5063 Operation the Sequence(Bestcoder Round #13)
- StringBuffer和StringBuilder存在的作用是什么
- blade and soul pvp guide
- blade and soul races guide
- UI设计 - iOS
- UI设计 - Web
- UI设计 - PPT
- STL与泛型编程<三>:deque
- UIActivityIndicatorView头文件学习
- IOS-UIDynamic
- iOS手势之UISwipeGestureRecognizer的正确用法
- POJ 2785 4 Values whose Sum is 0
- 关于UITableView中cell的重用问题
- UITextField实现PlaceHolder
- Unexpected Exception caught setting 'x' on class xx:Error setting expression 'xx' with value ['x',]
- UIActivity头文件学习
- swif之UITableViewCell和UITableView常见属性复习
- POJ 3061 Subsequence【尺取法】