c#组合算法

来源:互联网 发布:网络脆弱性的原因 编辑:程序博客网 时间:2024/06/06 18:47
public static IEnumerable<IEnumerable<TValue>> Combination<TValue>(            this IEnumerable<TValue> values,            Int32 count,            Int32 num)        {            var t = Enumerable.Range(0, num).ToList();            do            {                yield return values.Where((x, i) => t.Contains(i));            }            while (NextCombination(t, count, num));        }        public static bool NextCombination(List<int> ar, int num, int k)        {            if (ar.Count() != k) ar = Enumerable.Range(0, k).ToList();            bool changed = false, finished = false;            if (k > 0)            {                for (int i = k - 1; !changed && !finished; i--)                {                    if (ar[i] < (num - 1) - (k - 1) + i)                    {                        ar[i]++;                        if (i < k - 1)                        {                            for (int j = i + 1; j < k; j++)                            {                                ar[j] = ar[j - 1] + 1;                            }                        }                        changed = true;                    }                    finished = (i == 0);                }            }            return changed;        }    }

算法2:

public static List<List<T>> GetCombinationList<T>(List<T> elements, int m)        {            List<List<T>> result = new List<List<T>>();//存放返回的列表            List<List<T>> temp = null; //临时存放从下一级递归调用中返回的结果            List<T> oneList = null; //存放每次选取的第一个元素构成的列表,当只需选取一个元素时,用来存放剩下的元素分别取其中一个构成的列表;            T oneElment; //每次选取的元素            List<T> source = new List<T>(elements); //将传递进来的元素列表拷贝出来进行处理,防止后续步骤修改原始列表,造成递归返回后原始列表被修改;            int n = 0; //待处理的元素个数            if (elements != null)            {                n = elements.Count;            }            if (n == m && m != 1)//n=m时只需将剩下的元素作为一个列表全部输出            {                result.Add(source);                return result;            }            if (m == 1)  //只选取一个时,将列表中的元素依次列出            {                foreach (T el in source)                {                    oneList = new List<T>();                    oneList.Add(el);                    result.Add(oneList);                    oneList = null;                }                return result;            }            for (int i = 0; i <= n - m; i++)            {                oneElment = source[0];                source.RemoveAt(0);                temp = GetCombinationList(source, m - 1);                for (int j = 0; j < temp.Count; j++)                {                    oneList = new List<T>();                    oneList.Add(oneElment);                    oneList.AddRange(temp[j]);                    result.Add(oneList);                    oneList = null;                }            }            return result;        }