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# 構(gòu)造函數(shù)如何調(diào)用虛方法
這篇文章主要介紹了C# 構(gòu)造函數(shù)如何調(diào)用虛方法,文中講解非常詳細,示例代碼幫助大家更好的理解和學習,感興趣的朋友可以了解下2020-07-07C#?基于TCP?實現(xiàn)掃描指定ip端口的方式示例
本文主要介紹了C#基于TCP實現(xiàn)掃描指定ip端口的方式示例,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-11-11Unity?制作一個分數(shù)統(tǒng)計系統(tǒng)
項目中經(jīng)常遇到分數(shù)統(tǒng)計的需求,例如操作正確則計分,相反則不計分失去該項分數(shù),為了應(yīng)對需求需要一個分數(shù)統(tǒng)計系統(tǒng)。本文主要介紹了通過Unity實現(xiàn)這樣的一個計分系統(tǒng),快來跟隨小編一起學習吧2021-12-12