以下是我用来计算列表中元素的幂集的两段代码
代码1)
public static List<List<int>> getCpower(List<int> list)
{
var result = new List<List<int>>();
for (int i = 0; i < (1 << list.Count); i++)
{
var sublist = new List<int>();
for (int j = 0; j < list.Count; j++)
{ if ((i & (1 << j)) != 0)
{ sublist.Add(list[j]);
}
}
result.Add(sublist);
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
代码2)
public static List<List<int>> getCpower(List<int> list)
{
var result = new List<List<int>>();var sublist = new List<int>();
for (int i = 0; i < (1 << list.Count); i++)
{
sublist.Clear();sublist.TrimExcess();
for (int j = 0; j < list.Count; j++)
{ if ((i & (1 << j)) != 0)
{ sublist.Add(list[j]);
}
}
result.Add(sublist);
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
第一个代码使用了一个新语句,如果我试图查找列表的powersets,其数量为30,则会出现OutOfMemoryException.为了节省内存,我使用了Clear()和TrimExcess()来获取列表,好像它是使用新语句初始化的一样在code2中.但是这两个代码会返回不同的结果.我不明白为什么会这样.请帮忙.
以下两件作品是不是做同样的事情
for(....)
{
var sublist = new List<int>();
for(......)
{
//some code
}
}
Run Code Online (Sandbox Code Playgroud)
和
var sublist = new List<int>();
for(.....)
{
sublist.Clear();sublist.TrimExcess();
for(.... )
{
//some code
}
}
Run Code Online (Sandbox Code Playgroud)
在您的第二个代码中,您只有一个嵌套列表 - 您将添加几个引用相同子列表的引用,这是毫无意义的.
您是否认为可能是因为您的第一个代码占用空间不足的原因是因为您从根本上试图一次在内存中保留太多数据?
你可以考虑回复IEnumerable<List<int>>这样的:
public static IEnumerable<List<int>> getCpower(List<int> list)
{
for (int i = 0; i < (1 << list.Count); i++)
{
var sublist = new List<int>();
for (int j = 0; j < list.Count; j++)
{ if ((i & (1 << j)) != 0)
{
sublist.Add(list[j]);
}
}
yield return sublist;
}
}
Run Code Online (Sandbox Code Playgroud)
现在将对此进行延迟评估 - 因此您可以迭代顶级序列,但除非调用者保留列表,否则您一次只能在内存中有一个列表.
| 归档时间: |
|
| 查看次数: |
190 次 |
| 最近记录: |