我有10个字。如何获得 5 个单词的所有可能组合 (n=10, k=5)
。顺序无关紧要。
例如:“A”、“B”、“C”,如果 k=2(本例中为 n=3)
,则需要 AB、BC 和 AC。也许您知道一些有用的代码或示例。
附言对不起,如果我不够正确,因为我的英语不太好。
最佳答案
您要做的是获取集合的所有排列。
这是代码片段:
static void Main(string[] args)
{
var list = new List<string> { "a", "b", "c", "d", "e" };
var result = GetPermutations(list, 3);
foreach (var perm in result)
{
foreach (var c in perm)
{
Console.Write(c + " ");
}
Console.WriteLine();
}
Console.ReadKey();
}
static IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<T> items, int count)
{
int i = 0;
foreach (var item in items)
{
if (count == 1)
yield return new T[] { item };
else
{
foreach (var result in GetPermutations(items.Skip(i + 1), count - 1))
yield return new T[] { item }.Concat(result);
}
++i;
}
}
输出:
a b c
a b d
a b e
a c d
a c e
a d e
b c d
b c e
b d e
c d e
关于c# - 不重复的单词组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5132758/