今天一个朋友让我帮他做得一个集合排列的脑图算法。
Flex代码
private var dataAc:ArrayCollection = new ArrayCollection(["A","B","C","D"]);
protected function windowedapplication1_creationCompleteHandler(event:FlexEvent):void
{
var ch:String = "-";
for each(var s:String in dataAc)
{
trace(ch + s);
var sIndex:int = dataAc.getItemIndex(s);
var ac:ArrayCollection = ObjectUtil.clone(dataAc) as ArrayCollection;
ac.removeItemAt(sIndex);
getNext(ch+"-",s,ac)
}
}
private function getNext(str:String,prefix:String,ac:ArrayCollection):void
{
for each(var s1:String in ac)
{
trace(str + prefix+s1);
var sIndex:int = ac.getItemIndex(s1);
var ac1:ArrayCollection = ObjectUtil.clone(ac) as ArrayCollection;
ac1.removeItemAt(sIndex);
getNext(str+"-",prefix+s1,ac1)
}
}
Java代码
public class Test {
private static List<String> list = new ArrayList<String>();
public static void main(String[] args) {
list.add("A");
list.add("B");
list.add("C");
list.add("D");
//输出符号
String ch = "-";
for (int i =0;i<list.size();i++)
{
String s = list.get(i);
System.out.println(ch + s);
List<String> newLs = new ArrayList<String>();
newLs.addAll(list);
newLs.remove(i);
getNext(ch+"-",s,newLs);
}
}
private static void getNext(String str,String prefix,List<String> ac)
{
for (int i =0;i<ac.size();i++)
{
String s1 = ac.get(i);
System.out.println(str + prefix+s1);
List<String> newLs = new ArrayList<String>();
newLs.addAll(ac);
newLs.remove(i);
getNext(str+"-",prefix+s1,newLs);
}
}
}
输出结构:
-A
--AB
---ABC
----ABCD
---ABD
----ABDC
--AC
---ACB
----ACBD
---ACD
----ACDB
--AD
---ADB
----ADBC
---ADC
----ADCB
-B
--BA
---BAC
----BACD
---BAD
----BADC
--BC
---BCA
----BCAD
---BCD
----BCDA
--BD
---BDA
----BDAC
---BDC
----BDCA
-C
--CA
---CAB
----CABD
---CAD
----CADB
--CB
---CBA
----CBAD
---CBD
----CBDA
--CD
---CDA
----CDAB
---CDB
----CDBA
-D
--DA
---DAB
----DABC
---DAC
----DACB
--DB
---DBA
----DBAC
---DBC
----DBCA
--DC
---DCA
----DCAB
---DCB
----DCBA