CreatingaPowerSetofaSequence我正在尝试创建一个程序,它是创建序列、字符串或数字的可能组合的基础。这是某种加密/解密程序。我正在使用VisualStudio2013和C#。我想做的是从一个序列生成幂集,但我有点卡住了,无法继续。这是代码。publicstaticvoidrandomSeq(){inttemp=0;字符串序列=“1234”;StringBuildersb=newStringBuilder();char[]bits=seq.Select((charc)=>c).ToArray();Console.Write("给定序列:");控制台。写入(序列);控制台.WriteLine();Console.WriteLine("生成的可能性");foreach(chariteminbits){Console.WriteLine(item);}do{if(temp<=2){for(inti=temp+1;i2){for(intk=0;kPowerSet(thisIEnumerableitems){if(!items.Any())yieldreturnitems;//{{}}else{varhead=items.First();varpowerset=items.Skip(1).PowerSet().ToList();foreach(varsetinpowerset)产生返回集。前置(头);foreach(varsetinpowerset)yieldreturnset;}}合理的?—————更新——————Sergey正确地指出我的代码有SchlemielthePainter算法,因此消耗了大量的时间和内存;好赶上谢尔盖。这是一个使用不可变堆栈的高效版本:classImmutableList{publicstaticreadonlyImmutableListEmpty=newImmutableList(null,default(T));privateImmutableList(ImmutableListtail,Thead){this.Head=head;this.Tail=尾巴;}publicTHead{get;私有集;}publicImmutableListTail{get;私有集;}publicImmutableListPush(Thead){returnnewImmutableList(this,head);}publicIEnumerable>PowerSet(){if(this==Empty)yieldreturnthis;else{varpowerset=Tail.PowerSet();foreach(varsetinpowerset)yieldreturnset.Push(Head);foreach(varsetinpowerset)yieldreturnset;}SergeyS使用Linq提到的相同算法(其中inputSet是输入,outputPowerSet是输出):intsetLength=inputSet.Count;intpowerSetLength=1晚了,但为什么不在下面?它似乎比这里发布的建议要简单得多:以上是C#学习教程的全部内容:创建序列的幂集。如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注---/*Descriptionforasampleset{1,2,2,3}:Step1-Startwith{}:{}第2步-通过添加1来“扩展”先前的集合:{}---{1}第3步-扩展先前的通过添加第一个2来设置:{}{1}---{2}{1,2}第4步-通过添加第二个2来扩展之前的集合:{}{1}{2}{1,2}---{2}{1,2}{2,2}{1,2,2}第5步-通过添加3扩展之前的集合:{}{1}{2}{1,2}{2}{1,2}{2,2}{1,2,2}---{3}{1,3}{2,3}{1,2,3}{2,3}{1,2,3}{2,2,3}{1,2,2,3}元素总数=16(即2^4),符合预期。*/privatestaticvoidPowerSet(IListnums,refIList>output){//ToDo:验证参数output.Add(newList());ExpandSet(nums,0,ref输出);}privatestaticvoidExpandSet(IListnums,intpos,refIList>output){if(pos==nums.Count){return;}列表tmp;intitem=nums[pos];对于(inti=0,n=output.Count;i();tmp.AddRange(output[i]);tmp.Add(item);output.Add(tmp);}ExpandSet(nums,pos+1,refoutput);}本文收集自网络,不代表立场,如涉及侵权,请点击右边联系管理员删除,如需转载请注明出处: