问题描述
我需要生成{"a", "b","c"}
之间的所有可能组合.
I need to generate all possible combinations between {"a", "b","c"}
.
例如,一个输入集,例如{"a", "b","c"}
,预期输出是{"a", "b", "c" "ab", "ac", "bc", "abc"}
.
For example, an input set say like {"a", "b","c"}
, expected output is {"a", "b", "c" "ab", "ac", "bc", "abc"}
.
推荐答案
听起来您正在寻找的基本上是电源设置.这是一个简单的实现(摘自本网站):
It sounds like what you're looking for is basically a form of power set. Here's a simple implementation (taken from this site):
public IEnumerable<IEnumerable<T>> GetPowerSet<T>(this IList<T> list)
{
return from m in Enumerable.Range(0, 1 << list.Count)
select
from i in Enumerable.Range(0, list.Count)
where (m & (1 << i)) != 0
select list[i];
}
请注意,由于使用<<
运算符,您将无法对包含30个以上元素的列表使用此方法.无论如何,我不建议您尝试使用一个包含那么多元素的列表,因为结果包含30个元素,结果集将包含2 或1073741824个元素.
Note that thanks to the <<
operator, you won't be able to use this method with lists that have more than 30 elements. I wouldn't recommend trying it with a list with close to that many elements anyway, since at 30 elements, the result set would contain 2 or 1073741824 elements.
您可以使用这种方法来获得所需的结果
You can use this method to get the result you want like this
public IEnumerable<string> GetPermutations(IList<string> strings)
{
return from s in strings.GetPowerSet()
select string.Concat(s);
}
但是,由于幂集包括空集,因此实际上将返回结果{"", "a", "b", "c", "ab", "ac", "bc", "abc"}
.要过滤出空字符串,请使用以下命令:
However, because the power set includes the null set, this will actually return the result {"", "a", "b", "c", "ab", "ac", "bc", "abc"}
. To filter out the empty string, use this:
public IEnumerable<string> GetPermutations(IList<string> strings)
{
return from s in strings.GetPowerSet()
let str = string.Concat(s)
where str.Length > 0 // exclude null set result
select str;
}
或更简单地说:
public IEnumerable<string> GetPermutations(IList<string> strings)
{
return from s in strings.GetPowerSet().Skip(1)
select string.Concat(s);
}
这篇关于寻找可能的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!