高效生成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, Listcurrent, List > 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
nums, int start, List > 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
> combinations = new ArrayList<>(); for (int i = 2; i <= nums.length; i++) { combine(nums, 0, i, new ArrayList<>(), combinations); } List
> allPermutations = new ArrayList<>(); for (List
combination : combinations) { permutation(combination, 0, allPermutations); } System.out.println(allPermutations); } }
代码首先定义了combine
函数,该函数通过递归生成所有可能的组合。combine
函数调用permutation
函数来生成每种组合的所有排列。permutation
函数使用递归实现全排列,通过交换元素来遍历所有排列方式。main
函数驱动整个过程,从长度为2的组合开始,直到数组长度。该方案有效地穷举所有符合要求的组合和排列。