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; }
阅读全文
0 0
- c#组合算法整理
- C#组合算法
- 排列 组合 算法 C#
- C# 组合算法
- c#组合算法
- C#组合的递归算法
- c#全排列 和 组合算法
- 基于C#的排列和组合算法
- C# 有放回(重复)组合算法
- 算法练习 -- DP C# 实现 全组合算法
- 全排列和组合算法的C#语言实现
- 组合算法
- 组合算法
- 组合算法
- 组合算法
- 组合算法
- 组合算法
- 组合算法
- ZooKeeper的Znode剖析
- activiti源码获取
- 手机红外遥控器发送红外信号到STM32【HAL库】
- [自用门户]三种单双背景换色方法,二和三类似
- A Painless Q-learning Tutorial (一个 Q-learning 算法的简明教程)
- c#组合算法
- POJ 2104 K-th Number(主席树)
- 密室逃脱2 古堡迷城
- leetcode 7. Reverse Integer
- 2003搭建DVWA测试环境
- QT5.4设置应用程序图标
- 网络流24题-8
- 想知道支付宝(Android版)使用了哪些开源项目?
- python递归打印某个目录的内容