package w3ang.algorithms;
import java.util.ArrayList;
public class Combination
{
public static void main(String[] args) {
ArrayList<Integer>arrayList=new ArrayList<>();
arrayList.add(1);arrayList.add(2);arrayList.add(3);arrayList.add(4);
Combination combination=new Combination();
combination.listCombineAll(arrayList, new String(), 0, arrayList.size());
}
void listCombineAll(ArrayList<Integer>ar,String result, int s,int t)
{
//#对应的对
System.out.print("#: ");System.out.print("[#,#] ");
listSonCombine(ar, "#",result, 0, ar.size());
System.out.println();
//非空组合对应的对
listCombine(ar, result, s, t);
}
void listCombine(ArrayList<Integer>ar,String result, int s,int t)
{
for(int i=s;i<t;i++)
{
String new_result=result+ar.get(i);
System.out.print(new_result+": ");
//列出包含result+ar.get(i)的所有组合
@SuppressWarnings("unchecked")
ArrayList<Integer>arSon=(ArrayList<Integer>) ar.clone();
System.out.print("["+new_result+","+new_result+"] ");
for(int j=0;j<new_result.length();j++)
{
Integer integer=new_result.charAt(j)-('0'-0);
arSon.remove(integer);
}
listSonCombine(arSon,new_result,new_result, 0, arSon.size());
System.out.println();
listCombine(ar, new_result, i+1, t);
}
}
void listSonCombine(ArrayList<Integer>ar,String originResult, String result, int s,int t)
{
for(int i=s;i<t;i++)
{
String new_result=result+ar.get(i);
System.out.print("["+originResult+","+new_result+"] ");
listSonCombine(ar,originResult, new_result, i+1, t);
}
}
}
/*
#: [#,#] [#,1] [#,12] [#,123] [#,1234] [#,124] [#,13] [#,134] [#,14] [#,2] [#,23] [#,234] [#,24] [#,3] [#,34] [#,4]
1: [1,1] [1,12] [1,123] [1,1234] [1,124] [1,13] [1,134] [1,14]
12: [12,12] [12,123] [12,1234] [12,124]
123: [123,123] [123,1234]
1234: [1234,1234]
124: [124,124] [124,1243]
13: [13,13] [13,132] [13,1324] [13,134]
134: [134,134] [134,1342]
14: [14,14] [14,142] [14,1423] [14,143]
2: [2,2] [2,21] [2,213] [2,2134] [2,214] [2,23] [2,234] [2,24]
23: [23,23] [23,231] [23,2314] [23,234]
234: [234,234] [234,2341]
24: [24,24] [24,241] [24,2413] [24,243]
3: [3,3] [3,31] [3,312] [3,3124] [3,314] [3,32] [3,324] [3,34]
34: [34,34] [34,341] [34,3412] [34,342]
4: [4,4] [4,41] [4,412] [4,4123] [4,413] [4,42] [4,423] [4,43]
*/
Combination相关集合
最新推荐文章于 2024-09-13 07:30:00 发布