高效生成java数组中所有两位以上元素的组合和排列
本文介绍如何高效生成java数组中所有两位以上元素的组合和排列。例如,给定数组list1 = {11, 33, 22},我们需要找出所有可能的两位以上连续子序列及其所有排列,例如 {11, 33}、 {11, 22}、 {11, 33, 22}、 {11, 22, 33} 等。
我们将使用递归算法结合排列算法来实现。以下代码片段展示了如何利用递归函数combine生成所有可能的组合,以及permutation函数生成每种组合的所有排列:
import java.util.*; public class Test { public static void combine(int[] nums, int start, int k, List<Integer> current, List<List<Integer>> result) { if (k == 0) { result.add(new ArrayList<>(current)); return; } for (int i = start; i < nums.length - k + 1; i++) { current.add(nums[i]); combine(nums, i + 1, k - 1, current, result); current.remove(current.size() - 1); } } public static void permutation(List<Integer> nums, int start, List<List<Integer>> result) { if (start == nums.size()) { result.add(new ArrayList<>(nums)); return; } for (int i = start; i < nums.size(); i++) { Collections.swap(nums, start, i); permutation(nums, start + 1, result); Collections.swap(nums, start, i); // backtrack } } public static void main(String[] args) { int[] nums = {11, 33, 22}; List<List<Integer>> combinations = new ArrayList<>(); for (int i = 2; i <= nums.length; i++) { combine(nums, 0, i, new ArrayList<>(), combinations); } List<List<Integer>> allPermutations = new ArrayList<>(); for (List<Integer> combination : combinations) { permutation(combination, 0, allPermutations); } System.out.println(allPermutations); } }
代码首先定义了combine函数,该函数通过递归生成所有可能的组合。combine函数调用permutation函数来生成每种组合的所有排列。permutation函数使用递归实现全排列,通过交换元素来遍历所有排列方式。main函数驱动整个过程,从长度为2的组合开始,直到数组长度。该方案有效地穷举所有符合要求的组合和排列。