没有重复的单词组合

Dar*_*ria 7 c# string combinations words

我有10个字.如何获得5个单词的所有可能组合(n=10, k=5).订单无关紧要.

例如:"A", "B", "C", if k=2 (n=3 in this case),它想要AB,BC和AC.也许你知道一些有用的代码或例子.

PS对不起,如果我不够正确,因为我不太懂英语.

jrb*_*rly 17

你要做的是获得一个集合的所有排列.

这是代码片段:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

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 
Run Code Online (Sandbox Code Playgroud)

  • 在数学上更正确.您可以在不重复的情况下调用此组合(顺序并不重要)(项目最多可以出现1次或更少).https://www.mathsisfun.com/combinatorics/combinations-permutations.html (5认同)