C(n,m)排列组合算法

主要解决C(n,m)问题

    static class Extension
    {
        public static IList<IList<T>> GetGroup<T>(this IList<T> list, int size)
        {
            if (list.Count < size)
            {
                throw new ArgumentOutOfRangeException("size");
            }
            IList<IList<T>> result = GetGroup<T>(list, 0, size);
            return result;
        }

        private static IList<IList<T>> GetGroup<T>(IList<T> list, int index, int size)
        {
            IList<IList<T>> result = new List<IList<T>>();
            if (size > 0)
            {
                for (int i = index; i <= list.Count - size; i++)
                {
                    var group = GetGroup<T>(list, i + 1, size-1);
                    if (group.Count > 0)
                    {
                        foreach (var items in group)
                        {
                            List<T> item = new List<T>() { list[i] };
                            item.AddRange(items);
                            result.Add(item);
                        }
                    }
                    else
                    {
                        result.Add(new List<T>() { list[i] });
                    }
                }
            }
            return result;
        }
    }

 

posted @ 2019-04-26 11:21  Joe·Zhou  阅读(2676)  评论(0编辑  收藏  举报