C#中实现任意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;
}
}
}
推荐阅读