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)”时,结果不正确。怎么了?
答案 0 :(得分:0)
我明白了。由于result.add(list)只将list的引用添加到result。当列表内容发生变化时,结果中添加的内容也会发生变化。所以需要result.add(new ArrayList(list))。