词组合,而无需重复 [英] Words combinations without repetition

查看:124
本文介绍了词组合,而无需重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有10个字。我怎样才能获得的5个字所有可能的组合(N = 10,K = 5)。该订单的不要紧

I have 10 words. How can I get all possible combinations of 5 words (n=10, k=5). The order does not matter.

例如:A,B,C,如果k = 2(N =在这种情况下,3),它想AB,BC和AC。也许你知道一些有用的代码或例子。

For example: "A", "B", "C", if k=2 (n=3 in this case), it would like AB, BC and AC. Maybe you know some usefull code or example.

P.S。很抱歉,如果我没有足够的权利,因为我不知道英语非常好。

P.S. Sorry if I'm not right enough cause I don't know English very good.

推荐答案

你所试图做的是得到一个集合中的所有排列。

What you are trying to do is get all the permutations of a collection.

  • Unique permutations of list
  • permutations of k objects from a set of n algorithm

以下是代码片段:

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;
    }
}



输出:

Outputs:

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 

这篇关于词组合,而无需重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆