【问题标题】:return IList<IList<int>> is empty - why?return IList<IList<int>> 为空 - 为什么?
【发布时间】:2017-11-21 03:51:28
【问题描述】:

问题是返回一个包含数组所有排列的列表。由于某种原因,结果列表为空。事实是,我 100% 确定这与我在某处错误地使用 IList 或 List 有关,但老实说,必须将其返回为 IList&lt;IList&lt;int&gt;&gt; 确实令人困惑……我觉得这样做会更容易返回List&lt;List&lt;int&gt;&gt;,但我正在使用 leetcode 执行此操作,并尝试保留问题中写入的原始签名。当 currentPermutation.Count == nums.Length 时,我打印了 currnet 排列的值并打印了所有排列,所以我知道 currentPermutation 正在填充正确的数字..为什么结果列表不这样做呢?

public class Solution {

    public IList<IList<int>> Permute(int[] nums) {

        List<IList<int>> listOfPermutations = new List<IList<int>>();
        IList<int> currentPermutation = new List<int>();
        int[] elementsSeen = new int[nums.Length];
        Permute(listOfPermutations, nums, elementsSeen, currentPermutation);

        return (IList<IList<int>>)listOfPermutations;
    }


    public void Permute(List<IList<int>> list, int[] nums, int[] elementsSeen, IList<int> currentPermutation) {

        if (currentPermutation.Count == nums.Length) {
            list.Add(currentPermutation);
        }
        else {
        for (int i = 0; i < nums.Length; i++) {
            if (elementsSeen[i] == 0) {
                elementsSeen[i] = 1;
                currentPermutation.Add(nums[i]);
                Permute(list, nums, elementsSeen, currentPermutation);
                currentPermutation.RemoveAt(currentPermutation.Count - 1);
                elementsSeen[i] = 0;
            }
        }
     }
  }
}

【问题讨论】:

标签: c# list permutation


【解决方案1】:

您一遍又一遍地将相同的列表添加到结果中。最后你有n!指向相同的空列表的指针(currentPermutation 最终为空)。您只需为每个排列复制一份 List 并将新的 List 添加到结果中。

list.Add(currentPermutation.ToList()); //clone the list

“在列表上调用 ToList()”可能看起来有点棘手,您实际上是在 IEnumerable 上调用 ToList(),这样更好吗?重点是创建新的独立列表。

也许你并不完全理解 C# 中的 List 是什么。列表是一个对象。如果你将它添加到某处,你并没有将它直接添加到那里,你只需添加指向该对象的指针。

【讨论】:

  • 好吧..改变它的工作,但我真的不明白 ToList() 如何修复它..我在 List 上调用 ToList()?这甚至意味着什么?
  • @FrostyStraw 我添加了更多解释,希望对您有所帮助。
  • ToList 是一个 Linq 扩展方法,只是为了更清楚。除此之外,整个数据结构对我疲惫的大脑来说似乎非常麻烦。
  • @AntonínLejsek 好的,我可以更清楚地看到我如何将指针添加到同一个列表 6 次。每次回溯时,我都会从列表中删除最后一个元素,这一事实对于为什么每次都是空列表也是有意义的。然后调用 ToList() 只返回一个新列表,这就是传递给列表列表的其他 Add 方法的内容。这是正确的吗?
猜你喜欢
  • 2020-05-17
  • 1970-01-01
  • 1970-01-01
  • 2013-01-11
  • 2011-03-06
  • 1970-01-01
  • 1970-01-01
  • 2011-08-23
  • 1970-01-01
相关资源
最近更新 更多