C#中实现任意List的全组合算法代码
时间:2022-09-23 01:06:48
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 算法
{
class 全组合算法
{
[Flags]
public enum PersonType
{
Audit = 1,
Child = 2,
Senior = 4
}
public static void Run(string[] args)
{
var lstSource = GetEnumList<PersonType>();
var lstComb = FullCombination(lstSource);
var lstResult = new List<PersonType>();
lstComb.ForEach(item =>
{
lstResult.Add(item.Aggregate((result, source) => result | source));
});
}
public static List<T> GetEnumList<T>()
{
var lst = new List<T>();
foreach (T item in Enum.GetValues(typeof(T)))
{
lst.Add(item);
}
return lst;
}
//全组合算法
public static List<List<T>> FullCombination<T>(List<T> lstSource)
{
var n = lstSource.Count;
var max = 1 << n;
var lstResult = new List<List<T>>();
for (var i = 0; i < max; i++)
{
var lstTemp = new List<T>();
for (var j = 0; j < n; j++)
{
if ((i >> j & 1) > 0)
{
lstTemp.Add(lstSource[j]);
}
}
lstResult.Add(lstTemp);
}
lstResult.RemoveAt(0);
return lstResult;
}
}
}
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
SpringBoot整合TomCat实现本地图片服务器代码解析
积累Visual Studio 常用快捷键的动画演示
![](https://img.aspxhome.com/file/2023/1/100121_0s.gif)
java 的Collection接口实例详解
C#遍历文件夹获取指定后缀名文件
![](https://img.aspxhome.com/file/2023/6/129696_0s.jpg)
c# 委托和事件实例学习
springboot如何使用logback-spring配置日志格式,并分环境配置
![](https://img.aspxhome.com/file/2023/6/58766_0s.png)
Java中多媒体文件上传及页面回显的操作代码
![](https://img.aspxhome.com/file/2023/2/66202_0s.png)
Android 13新功能及适配工作详解
JAVA面试题 从源码角度分析StringBuffer和StringBuilder的区别
![](https://img.aspxhome.com/file/2023/3/95463_0s.png)
Java移动文件夹及其所有子文件与子文件夹
Android触屏测试实例代码
Spring实现处理跨域请求代码详解
C#中三种Timer计时器的详细用法
面试中遇到的java逃逸分析问题
SpringBoot整合RabbitMQ实现消息确认机制
![](https://img.aspxhome.com/file/2023/2/108472_0s.png)
通过IDEA快速定位和排除依赖冲突问题
![](https://img.aspxhome.com/file/2023/9/71919_0s.png)
c# 动态构建LINQ查询表达式
![](https://img.aspxhome.com/file/2023/2/77252_0s.png)
Android使用SQLite数据库的示例
![](https://img.aspxhome.com/file/2023/1/139371_0s.png)
基于Java编写串口通信工具
![](https://img.aspxhome.com/file/2023/9/93069_0s.jpg)