要实现全排列的递归算法,可以按照以下步骤进行:
-
定义一个递归函数,传入当前需要排列的数组、起始索引和结束索引。
-
当起始索引等于结束索引时,表示已经遍历到数组的最后一个元素,此时输出当前排列结果。
-
否则,通过循环将当前需要排列的数组中的每个元素与起始索引进行交换,然后递归调用函数,将起始索引加1,继续进行下一轮的排列。
-
在递归函数内,每次递归都会产生一个新的排列,当递归返回时,需要将交换过的元素交换回来,以保持数组的原始顺序。
以下是Java代码实现:
import java.util.Arrays; public class Permutation { public static void permutation(int[] nums, int start, int end) { if (start == end) { System.out.println(Arrays.toString(nums)); } else { for (int i = start; i <= end; i++) { swap(nums, start, i); // 将当前元素与起始索引交换 permutation(nums, start + 1, end); // 递归调用,起始索引加1 swap(nums, start, i); // 将交换过的元素交换回来 } } } public static void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } public static void main(String[] args) { int[] nums = {1, 2, 3}; permutation(nums, 0, nums.length - 1); } }
运行以上代码,将会输出全排列的结果:
[1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 2, 1] [3, 1, 2]