这篇文章主要介绍java如何实现排列组合算法,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!java排列组合算法[@more@]import java.util.ArrayList;import j
这篇文章主要介绍java如何实现排列组合算法,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
java排列组合算法[@more@]import java.util.ArrayList;import java.util.List;public class TestComposite {public static void main(String[] args) {// List allList = getFirstData();// List allList = getSecondData();List allList = getThirdData();List targetList = combinatePlan(allList);System.out.println(targetList);}private static List combinatePlan(List sourceList) {int[] subSizeArray;int[] subCountArray;int sourceCount = sourceList.size(); // 大list的长度subSizeArray = new int[sourceCount];subCountArray = new int[sourceCount];// 子list当前的值int targetCount = 1;for (int i = 0; i < sourceCount; i++) {List subList = (List) sourceList.get(i);int size = subList.size();subSizeArray[i] = size; // 存放每个子list的长度targetCount *= size; // 最终要返回的list长度subCountArray[i] = 0; // 从0开始 每个都是0// a.println("subCountArray[i]:"+subCountArray[i]);}List targetList = new ArrayList(targetCount);// targetCountfor (int i = 0; i < targetCount; i++) {// 记录每个结果应该包含的元素个数List targetSub = new ArrayList(sourceCount);for (int k = 0; k < sourceCount; k++) {int subIndex = subCountArray[k];targetSub.add(((List) sourceList.get(k)).get(subIndex));}addCount(subSizeArray, subCountArray);targetList.add(targetSub);}return targetList;}private static void addCount(int[] subSizeArray, int[] subCountArray) {// subCountArray数组的每个元素都是0 但是个数来记录循环要取的位置for (int i = subCountArray.length - 1; i >= 0; i--) {if (subCountArray[i] < subSizeArray[i] - 1) {subCountArray[i]++;return;} else {subCountArray[i] = 0;}}}private static List getFirstData(){List list1 = new ArrayList();list1.add("王一");list1.add("王二");list1.add("王三");List list2 = new ArrayList();list2.add("张一");list2.add("张二");list2.add("张三");List allList = new ArrayList();allList.add(list1);allList.add(list2);return allList;}private static List getSecondData(){List list1 = new ArrayList();list1.add("王一");list1.add("王二");List list2 = new ArrayList();list2.add("张一");list2.add("张二");List list3 = new ArrayList();list3.add("刘一");list3.add("刘二");List allList = new ArrayList();allList.add(list1);allList.add(list2);allList.add(list3);return allList;}private static List getThirdData(){List list1 = new ArrayList();list1.add("王一");list1.add("王二");List list2 = new ArrayList();list2.add("张一");List allList = new ArrayList();allList.add(list1);allList.add(list2);return allList;}}
以上是“java如何实现排列组合算法”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注编程网精选频道!
--结束END--
本文标题: java如何实现排列组合算法
本文链接: https://lsjlt.com/news/232027.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0