温馨提示×

java全排列用递归怎么实现

小亿
142
2023-08-11 10:48:43
栏目: 编程语言

要实现全排列的递归算法,可以按照以下步骤进行:

  1. 定义一个递归函数,传入当前需要排列的数组、起始索引和结束索引。

  2. 当起始索引等于结束索引时,表示已经遍历到数组的最后一个元素,此时输出当前排列结果。

  3. 否则,通过循环将当前需要排列的数组中的每个元素与起始索引进行交换,然后递归调用函数,将起始索引加1,继续进行下一轮的排列。

  4. 在递归函数内,每次递归都会产生一个新的排列,当递归返回时,需要将交换过的元素交换回来,以保持数组的原始顺序。

以下是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] 

0