【Java.算法】用于产生数组全排列结果的工具类Arranger
【代码】
import java.util.ArrayList; import java.util.List; /** * 用于产生数组全排列结果的工具类 * @since 2023/4/21 */ public class Arranger { // 保存在内部的原始元素数组的引用 private int[] rawArr; // 返回结果 private List<List<Integer>> results; /** * 构造函数 * * @param raws 原始元素数组 */ public Arranger(int[] raws) { rawArr = raws; results = new ArrayList<>(); doArrange(new ArrayList<>()); } /** * 使用递归进行全排列,结果放在results中 * * @param initialList 初始链表 */ private void doArrange(List<Integer> initialList) { List<Integer> innerList = new ArrayList<>(initialList); if (rawArr.length == initialList.size()) { results.add(innerList); } for (int i = 0; i < rawArr.length; i++) { if (innerList.contains(rawArr[i])) { continue; } innerList.add(rawArr[i]); doArrange(innerList); innerList.remove(innerList.size() - 1); } } /** * 获得结果链表的引用 * * @return */ public List<List<Integer>> getResults() { return results; } // 测试 public static void main(String[] args) { int[] numbers = { 1, 2, 3, 4, 5, 6 }; Arranger arranger = new Arranger(numbers); int idx = 0; for (List<Integer> re : arranger.getResults()) { System.out.println(String.format("%02d", ++idx) + "." + re); } } }
【对1,2,3的全排列】
01.[1, 2, 3] 02.[1, 3, 2] 03.[2, 1, 3] 04.[2, 3, 1] 05.[3, 1, 2] 06.[3, 2, 1]
【对1,2,3,4的全排列】
01.[1, 2, 3, 4] 02.[1, 2, 4, 3] 03.[1, 3, 2, 4] 04.[1, 3, 4, 2] 05.[1, 4, 2, 3] 06.[1, 4, 3, 2] 07.[2, 1, 3, 4] 08.[2, 1, 4, 3] 09.[2, 3, 1, 4] 10.[2, 3, 4, 1] 11.[2, 4, 1, 3] 12.[2, 4, 3, 1] 13.[3, 1, 2, 4] 14.[3, 1, 4, 2] 15.[3, 2, 1, 4] 16.[3, 2, 4, 1] 17.[3, 4, 1, 2] 18.[3, 4, 2, 1] 19.[4, 1, 2, 3] 20.[4, 1, 3, 2] 21.[4, 2, 1, 3] 22.[4, 2, 3, 1] 23.[4, 3, 1, 2] 24.[4, 3, 2, 1]
【对1,2,3,4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