C#中實現(xiàn)任意List的全組合算法代碼
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;
}
}
}
相關(guān)文章
C#?Windows?Forms中實現(xiàn)控件之間的連接線的方法詳解
這篇文章主要為大家詳細(xì)介紹了如何在C#?Windows?Forms應(yīng)用程序中實現(xiàn)繪圖工具中多個控件之間的連接線功能,文中的示例代碼講解詳細(xì),需要的可以參考下2024-02-02
C# MVC模式中應(yīng)該怎樣區(qū)分應(yīng)用程序邏輯(Controller層)和業(yè)務(wù)邏輯(Model層)?
這篇文章主要介紹了C# MVC模式中應(yīng)該怎樣區(qū)分應(yīng)用程序邏輯(Controller層)和業(yè)務(wù)邏輯(Model層)?,這也小編做.NET項目時經(jīng)常思考和讓人混亂的一個問題,這篇文章寫的挺好,一下清晰了許多,需要的朋友可以參考下2015-06-06

