> 文章列表 > java实现的列表组合算法

java实现的列表组合算法

java实现的列表组合算法

不废话,直接上代码:

package com.lj.luoye.util;import java.util.ArrayList;
import java.util.List;public class AnalysisUtil {//获取列表元素的组合列表,startIndex为列表开始下标,endIndex为列表结束下标public static List<List<Integer>> getPermutationList(int startIndex, int endIndex){List<List<Integer>> listList=new ArrayList<List<Integer>>();for(int i=startIndex; i<=endIndex;i++){//选出i的单个元素组合List<Integer> list=new ArrayList<Integer>();list.add(i);listList.add(list);//选出i之后的所有组合,并将这些组合合并上iif(i<endIndex){//endIndex之后没有元素了,所有不用选endIndex之后的所有组合List<List<Integer>> listList1=getPermutationList(i+1, endIndex);for(List<Integer> list1:listList1){List<Integer> listNew=new ArrayList<Integer>();listNew.addAll(list);listNew.addAll(list1);listList.add(listNew);}}}return listList;}//获取组合下标列表public static List<List<Integer>> getCombines(int allCount,int combineSize){List<List<Integer>> permutationList = getPermutationList(0, allCount-1);List<List<Integer>> combineList=new ArrayList<>();for(List<Integer> p:permutationList){if(p.size()==combineSize){combineList.add(p);}}return combineList;}//testpublic static void main(String[] args) {//4个元素的列表,1到4个元素的所有组合List<List<Integer>> permutationList = getPermutationList(0,3);System.out.println("Permutation:"+permutationList);System.out.println("Permutation size:"+permutationList.size());//7选6List<List<Integer>> combines = getCombines(7, 6);System.out.println("combines:"+ combines);System.out.println("combines size:"+ combines.size());}}