52. N-Queens II
2016-03-01 14:17
369 查看
public class Solution { private final static Set<Integer> occupiedCols = new HashSet<Integer>(); private final static Set<Integer> occupiedDiag1s = new HashSet<Integer>(); private final static Set<Integer> occupiedDiag2s = new HashSet<Integer>(); public static int totalNQueens(int n) { return totalNQueensHelper(0, 0, n); } private static int totalNQueensHelper(int row, int count, int n) { for (int col = 0; col < n; col++) { if (occupiedCols.contains(col)) continue; int diag1s = row + col; if (occupiedDiag1s.contains(diag1s)) continue; int diag2s = row - col; if (occupiedDiag2s.contains(diag2s)) continue; if(row == n-1) count++; else { occupiedCols.add(col); occupiedDiag1s.add(diag1s); occupiedDiag2s.add(diag2s); count = totalNQueensHelper(row+1, count, n); occupiedCols.remove(col); occupiedDiag1s.remove(diag1s); occupiedDiag2s.remove(diag2s); } } return count; } }
相关文章推荐
- easyui 学习总结
- NGUI点透问题
- 正则表达式匹配 a href链接,和input里面的value值
- fluidity install on Cluster
- UILabel 整理
- UIButton 整理
- ThreadPoolExecutor使用和思考(上)-线程池大小设置与BlockingQueue的三种实现区别
- 探秘Java中String、StringBuilder以及StringBuffer
- SPOJ QTREE4 - Query on a tree IV 树分治
- UIKit框架(20)表格视图UITableView
- iOS-UIScrollView拉伸效果
- BIOS与UEFI、MBR和GPT(转)
- 一个UIButton控件的状态设置和事件的执行
- GUI 关于JComboBox的用法
- IOS-55-UILable文字两边对齐的实现方式
- .Net Telerik Web UI 安装和使用入门
- 关于requirejs和grunt压缩合并是否矛盾
- UITabbar相关
- DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
- mssql-异常value '0000-00-00' can not be represented as java.sql.Date