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#解析char型指針?biāo)赶虻膬?nèi)容(實例解析)
在c++代碼中定義了一個功能函數(shù),這個功能函數(shù)會將計算的結(jié)果寫入一個字符串型的數(shù)組中output,然后c#會調(diào)用c++導(dǎo)出的dll中的接口函數(shù),然后獲取這個output并解析成string類型,本文通過實例解析C#?char型指針?biāo)赶虻膬?nèi)容,感興趣的朋友一起看看吧2024-03-03
C# 構(gòu)造函數(shù)如何調(diào)用虛方法
這篇文章主要介紹了C# 構(gòu)造函數(shù)如何調(diào)用虛方法,文中講解非常詳細(xì),示例代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-07-07
C#?基于TCP?實現(xiàn)掃描指定ip端口的方式示例
本文主要介紹了C#基于TCP實現(xiàn)掃描指定ip端口的方式示例,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-11-11
Unity?制作一個分?jǐn)?shù)統(tǒng)計系統(tǒng)
項目中經(jīng)常遇到分?jǐn)?shù)統(tǒng)計的需求,例如操作正確則計分,相反則不計分失去該項分?jǐn)?shù),為了應(yīng)對需求需要一個分?jǐn)?shù)統(tǒng)計系統(tǒng)。本文主要介紹了通過Unity實現(xiàn)這樣的一個計分系統(tǒng),快來跟隨小編一起學(xué)習(xí)吧2021-12-12

