【问题标题】:Some confusion in a solution to Leetcode NQueenLeetcode NQueen 解决方案中的一些混淆
【发布时间】: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


    【解决方案1】:

    我明白了。由于 result.add(list) 仅将列表的引用添加到结果中。当列表的内容发生变化时,结果中添加的东西也会发生变化。所以需要 result.add(new ArrayList(list)) 。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-19
      相关资源
      最近更新 更多