问题是返回一个包含数组所有排列的列表。由于某种原因,结果列表为空。事实是,我100%肯定它与我在某处使用IList或List错误有关,但它真的很混乱,必须将它作为IList<IList<int>>
返回...我觉得它会更容易只返回List<List<int>>
,但我是通过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;
}
}
}
}
}
答案 0 :(得分:4)
您可以反复向结果中添加相同的List。最后你有n!指向相同的空列表(currentPermutation
最后为空)。您只需为每个排列复制List,并将新列表添加到结果中。
list.Add(currentPermutation.ToList()); //clone the list
“在列表上调用ToList()”可能看起来有点棘手,你实际上是在IEnumerable上调用ToList(),那更好吗?关键是要创建新的独立List。
也许你并不完全理解C#中的List是什么。列表是一个对象。如果你在某处添加它,你不会在那里添加它,你只需添加指向这个对象的指针。