leetcode 52. N-Queens II
2017-07-03 16:08
337 查看
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
![](https://leetcode.com/static/images/problemset/8-queens.png)
这个和上一道题没什么区别,最后返回size就好
public class Solution {
public int totalNQueens(int n) {
List<List<String>>res = new ArrayList<List<String>>();
helper(n,0,new int
,res);
return res.size();
}
public void helper(int n,int row,int []columnForRow,List<List<String>>res){
if(n==row){
List<String>a = new ArrayList<String>();
for(int i=0;i<n;i++){
StringBuilder sb = new StringBuilder();
for(int j=0;j<n;j++){
if(columnForRow[i]!=j){
sb.append('.');
}
else sb.append('Q');
}
a.add(sb.toString());
}
res.add(new ArrayList<String>(a));
return ;
}
for(int i=0;i<n;i++){
columnForRow[row]=i;
if(check(row,columnForRow)){
helper(n,row+1,columnForRow,res);
}
}
}
public boolean check(int row,int []columnForRow){
for(int i=0;i<row;i++){
if(columnForRow[i]==columnForRow[row]|| Math.abs(columnForRow[row]-columnForRow[i])==row-i)return false;
}
return true;
}
}
Now, instead outputting board configurations, return the total number of distinct solutions.
![](https://leetcode.com/static/images/problemset/8-queens.png)
这个和上一道题没什么区别,最后返回size就好
public class Solution {
public int totalNQueens(int n) {
List<List<String>>res = new ArrayList<List<String>>();
helper(n,0,new int
,res);
return res.size();
}
public void helper(int n,int row,int []columnForRow,List<List<String>>res){
if(n==row){
List<String>a = new ArrayList<String>();
for(int i=0;i<n;i++){
StringBuilder sb = new StringBuilder();
for(int j=0;j<n;j++){
if(columnForRow[i]!=j){
sb.append('.');
}
else sb.append('Q');
}
a.add(sb.toString());
}
res.add(new ArrayList<String>(a));
return ;
}
for(int i=0;i<n;i++){
columnForRow[row]=i;
if(check(row,columnForRow)){
helper(n,row+1,columnForRow,res);
}
}
}
public boolean check(int row,int []columnForRow){
for(int i=0;i<row;i++){
if(columnForRow[i]==columnForRow[row]|| Math.abs(columnForRow[row]-columnForRow[i])==row-i)return false;
}
return true;
}
}
相关文章推荐
- <LeetCode OJ> 52. N-Queens II
- LeetCode-52. N-Queens II (JAVA)(N皇后解集个数)
- leetcode-52. N-Queens II
- leetcode 52. N-Queens II
- LeetCode 52. N-Queens II(N皇后)
- leetcode52. N-Queens II
- [LeetCode] 52. N-Queens II
- LeetCode 52. N-Queens II
- leetcode-52. N-Queens II
- LeetCode 52. N-Queens II
- 【LeetCode】52.N-Queens II(hard)解题报告
- leetcode 52. N-Queens II
- Leetcode 51. N-Queens && 52. N-Queens II(Hard)
- LeetCode 52. N-Queens II
- LeetCode||52. N-Queens II
- leetcode 52. N-Queens II
- LeetCode-51. N-Queens和LeetCode-52. N-Queens II
- (Java)LeetCode-52. N-Queens II
- 个人记录-LeetCode 52. N-Queens II
- LeetCode | 52.N-Queens II