【发布时间】:2016-04-20 12:38:03
【问题描述】:
public class Solution {
Set<Integer> column = new HashSet<Integer>();
Set<Integer> diag1 = new HashSet<Integer>();
Set<Integer> diag2 = new HashSet<Integer>();
public List<List<String>> solveNQueens(int n) {
ArrayList<List<String>> result = new ArrayList<List<String>>();
ArrayList<String> list = new ArrayList<String>();
dfs(result, list, 0, n);
return result;
}
private void dfs(ArrayList<List<String>> result, ArrayList<String> list,
int row, int n) {
if (row == n) {
result.add(new ArrayList<String>(list));
// Why I have to "result.add(new ArrayList<String>(list))"?
// Why can't I just "result.add(list)"?
return;
}
for (int j = 0; j < n; j++) {
if (column.contains(j) || diag1.contains(row + j)
|| diag2.contains(row - j))// check if there are other
// queens in the same column,
// diagonal1 or diagonal2
continue;
char[] rowChar = new char[n];
Arrays.fill(rowChar, '.');
rowChar[j] = 'Q';
String str = new String(rowChar);
list.add(str);
column.add(j);
diag1.add(row + j);
diag2.add(row - j);
dfs(result, list, row + 1, n);
// remove the queen and the constraints
list.remove(list.size() - 1);
column.remove(j);
diag1.remove(row + j);
diag2.remove(row - j);
}
}
这是 Leetcode 中的 N-Queens 问题。我找到了问题的解决方案,但我有一个问题,我在代码中发表了评论。 为什么我必须“result.add(new ArrayList(list))”? 为什么我不能只使用“result.add(list)”? 因为当我使用“result.add(list)”时,结果不正确。它有什么问题?
【问题讨论】:
标签: java arraylist depth-first-search