输出1,2,n这组数中随便三个数的不重复组合
输出1,2,...,n这组数中任意三个数的不重复组合
/** * 有一组数1,2,3,4,5输出不重复的由其中三个数组成的组合。 * [123, 124, 125, 134, 135, 145, 234, 235, 245, 345] */ public static void main(String[] args) { List<String> list = new ArrayList<String>();//[1, 2, 3, 4, 5] for(int i=0;i<5;i++){ list.add(new Integer(i+1).toString()); } List<String> tmp1,tmp2,a; List<List<String>> flag = new ArrayList<List<String>>(); List<String> result = new ArrayList<String>(); String str1,str2,str3; for(int j=0;j<list.size();j++){ //获取第一个数 str1 = list.get(j); tmp1 = new ArrayList<String>(list); //tmp1 = list;如果直接针对tmp1进行赋值将会影响到list的值,故需要使用带参数的构造方法赋值。 tmp1.remove(j); for (int m = 0; m < tmp1.size(); m++) { //获取第二个数 str2=tmp1.get(m); tmp2 = new ArrayList<String>(tmp1); tmp2.remove(m); for(int n=0; n<tmp2.size();n++){ //获取第三个参数 str3=tmp2.get(n); a = new ArrayList<String>(); a.add(str1); a.add(str2); a.add(str3); Collections.sort(a); //过滤重复纪录 if(!flag.contains(a)){ result.add(str1+str2+str3); flag.add(a); } } } } System.out.println(result); }
这是一个典型的组合问题,根据组合公式:C(n,m)=n!/(n-m)!m!,可以得出从5个数中取出3个不重复的数有10组不重复组合。
结果:[123, 124, 125, 134, 135, 145, 234, 235, 245, 345]