【发布时间】:2017-11-21 03:51:28
【问题描述】:
问题是返回一个包含数组所有排列的列表。由于某种原因,结果列表为空。事实是,我 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;
}
}
}
}
}
【问题讨论】:
-
可以看链接Permution
标签: c# list permutation