【发布时间】:2020-06-18 05:24:34
【问题描述】:
我正在尝试创建一个返回集合的所有子集的方法。
例如,如果我有集合 10,20,30,我希望得到以下输出
return new List<List<int>>()
{
new List<int>(){10},
new List<int>(){20},
new List<int>(){30},
new List<int>(){10,20},
new List<int>(){10,30},
new List<int>(){20,30},
//new List<int>(){20,10}, that substet already exists
// new List<int>(){30,20}, that subset already exists
new List<int>(){10,20,30}
};
因为集合也可以是字符串的集合,例如我想创建一个泛型方法。这是我已经解决的based on this solution。
static void Main(string[] args)
{
Foo<int>(new int[] { 10, 20, 30});
}
static List<List<T>> Foo<T>(T[] set)
{
// Init list
List<List<T>> subsets = new List<List<T>>();
// Loop over individual elements
for (int i = 1; i < set.Length; i++)
{
subsets.Add(new List<T>(){set[i - 1]});
List<List<T>> newSubsets = new List<List<T>>();
// Loop over existing subsets
for (int j = 0; j < subsets.Count; j++)
{
var tempList = new List<T>();
tempList.Add(subsets[j][0]);
tempList.Add(subsets[i][0]);
var newSubset = tempList;
newSubsets.Add(newSubset);
}
subsets.AddRange(newSubsets);
}
// Add in the last element
//subsets.Add(set[set.Length - 1]);
//subsets.Sort();
//Console.WriteLine(string.Join(Environment.NewLine, subsets));
return null;
}
编辑
对不起,我仍然得到重复...
static List<List<T>> GetSubsets<T>(IEnumerable<T> Set)
{
var set = Set.ToList<T>();
// Init list
List<List<T>> subsets = new List<List<T>>();
subsets.Add(new List<T>()); // add the empty set
// Loop over individual elements
for (int i = 1; i < set.Count; i++)
{
subsets.Add(new List<T>(){set[i - 1]});
List<List<T>> newSubsets = new List<List<T>>();
// Loop over existing subsets
for (int j = 0; j < subsets.Count; j++)
{
var newSubset = new List<T>();
foreach(var temp in subsets[j])
newSubset.Add(temp);
newSubset.Add(set[i]);
newSubsets.Add(newSubset);
}
subsets.AddRange(newSubsets);
}
// Add in the last element
subsets.Add(new List<T>(){set[set.Count - 1]});
//subsets.Sort();
return subsets;
}
然后我可以将该方法称为:
【问题讨论】:
-
我想得到一个集合的所有子集。如果我有集合 {1,2,3} 我想得到 {1},{2},{3},{1,2},{1,3},{2,3},{1, 2,3} .
-
您当前的代码有什么特别的问题?什么不起作用?
-
输入中的元素是否不同?如果没有,您想如何处理重复项?
-
如果您不知道集合的所有子集的含义,请尝试回答另一个问题。我不想听起来很抱歉,但我只想完成这项作业,非常感谢您的帮助。也许我应该将问题命名为获取集合的所有子集,但由于我将其与 c# 相关联,因此我想将集合传递给方法,而子集是列表或数组,这就是为什么我想要
List<List<T>>作为输出的原因我正在尝试创建的方法。 -
@TonoNam:我认为人们理解子集问题。不清楚的不是你想要做什么,而是你正在努力解决什么问题。