lintcode-medium-N Queens II
2016-04-01 16:32
531 查看
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
Example
For n=4, there are 2 distinct solutions.
Now, instead outputting board configurations, return the total number of distinct solutions.
Example
For n=4, there are 2 distinct solutions.
class Solution { /** * Calculate the total number of distinct N-Queen solutions. * @param n: The number of queens. * @return: The total number of distinct solutions. */ public int totalNQueens(int n) { //write your code here ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>(); if(n <= 0) return 0; int[] position = new int ; helper(result, 0, position, n); return result.size(); } public void helper(ArrayList<ArrayList<String>> result, int row, int[] position, int n){ if(row == n){ ArrayList<String> solution = new ArrayList<String>(); for(int i = 0; i < n; i++){ StringBuilder line = new StringBuilder(); for(int j = 0; j < n; j++){ if(j == position[i]) line.append('Q'); else line.append('.'); } solution.add(line.toString()); } result.add(new ArrayList<String>(solution)); return; } for(int i = 0; i < n; i++){ position[row] = i; if(valid(position, row, n)) helper(result, row + 1, position, n); } return; } public boolean valid(int[] position, int row, int n){ for(int i = row - 1; i >= 0; i--){ if(position[row] == position[i] || Math.abs(position[row] - position[i]) == row - i) return false; } return true; } };
相关文章推荐
- lintcode-medium-N Queens
- UITextField 解决限制文字长度不准确的问题
- Vue.js实例练习
- 仿 UIAlertView动画效果
- Android之UI控件
- 【转载】循环结构中break、continue、return和exit的区别
- iOS-------UITableView
- The request sent by the client was syntactically incorrect
- 随记(八)--图片排版UIViewContentMode
- Recover lost Confluence password
- 设置UITableView cell的左边距
- 快排QuickSort
- pyinstaller ImportError: The 'packaging' package is required; ...
- iOS学习笔记12--纯代码实现原生UITabBarController,手势滑动切换视图
- UI控件的事件监听
- iOS开发 ☞ UILable详解
- iOS开发-UIView之动画效果的实现方法
- UIDynamicAnimator简述
- 去掉uitableveiw多余的分割线
- android之在activity中控制另一个activity的UI更新_如何在activity之间传递handler