本文介紹如何高效生成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的組合開始,直到數組長度。該方案有效地窮舉所有符合要求的組合和排列。
立即學習“Java免費學習筆記(深入)”;
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END
喜歡就支持一下吧
相關推薦