
高效穷举两位以上组合方式
在 java 中,如何高效穷举列表中两位以上的所有组合方式?例如,给定列表 list1 = [11, 33, 22],我们希望能穷举出以下任意组合:
[11, 33]、[11, 22]、[11, 33, 22]、[11, 22, 33]、[33, 22]、[33, 11]、[33, 11, 22]、[33, 22, 11]、[22, 11]、[22, 33]、[22, 33, 11]、[22, 11, 33]
解决方案
我们可以使用递归和排列实现高效的组合枚举。
立即学习“Java免费学习笔记(深入)”;
1. 递归生成组合
递归函数 combine() 生成不同数量的组合。它取数量 i 为参数,并用数组 temp 存储组合。
combine() 逐个从列表 nums 中选择元素,填充 temp 数组,然后调用自身,直到 temp 已满。
有道小P
有道小P,新一代AI全科学习助手,在学习中遇到任何问题都可以问我。
64 查看详情
2. 排列组合元素
函数 permutation() 对组合元素进行排列。它使用启发式算法,将排列的复杂度从 o(n!) 降低到 o(n^2)。
3. 交换元素
函数 swap() 用于交换数组中两个元素的位置。
代码示例
import java.util.*;public class Test { public static void main(String[] args) { int[] nums = { 11, 33, 22 }; for (int i = 2; i <= nums.length; i++) { combine(nums, new int[i], 0, 0); } } public static void combine(int[] nums, int[] temp, int start, int index) { if (index == temp.length) { permutation(temp, 0, temp.length - 1); return; } for (int i = start; i < nums.length; i++) { temp[index] = nums[i]; combine(nums, temp, i + 1, index + 1); } } public static void permutation(int[] arr, int start, int end) { if (start == end) { System.out.println(Arrays.toString(arr)); } else { for (int i = start; i <= end; i++) { swap(arr, start, i); permutation(arr, start + 1, end); swap(arr, start, i); } } } public static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }}
结果
运行此代码将生成给定列表中所有可能的两位以上组合。
以上就是Java中如何高效穷举列表中两位以上元素的所有组合?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/384529.html
微信扫一扫
支付宝扫一扫