首页 >后端开发 >C++ >如何使用递归方法生成唯一整数数组的所有可能排列?

如何使用递归方法生成唯一整数数组的所有可能排列?

Patricia Arquette
Patricia Arquette原创
2024-12-23 14:14:15865浏览

How can I generate all possible permutations of an array of unique integers using a recursive approach?

生成数组的排列

理解问题

我们得到一个唯一整数数组,并要求生成所有可能的排列。如果两个排列的元素顺序不同,则它们被视为不同。对于长度为 n 的数组,有 n! 种可能的排列。

方法:递归排列

解决方案涉及两个主要步骤:

  1. 递归:取每个
  2. 交换:将当前元素与剩余部分的元素交换,以创建新的排列。

使用这种方法,我们可以生成所有排列。

代码实现

import java.util.ArrayList;
import java.util.List;

public class Permutation {

    public static List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        permute(nums, 0, result);
        return result;
    }

    private static void permute(int[] nums, int startIndex, List<List<Integer>> result) {
        if (startIndex == nums.length - 1) {
            // Base case: If we reach the end of the array, add the current permutation to the result.
            List<Integer> permutation = new ArrayList<>();
            for (int num : nums) {
                permutation.add(num);
            }
            result.add(permutation);
        } else {
            // Recursive case: Permute the remaining elements for each element at the current index.
            for (int i = startIndex; i < nums.length; i++) {
                swap(nums, startIndex, i);
                permute(nums, startIndex + 1, result);
                swap(nums, startIndex, i);
            }
        }
    }

    private static void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

使用示例

int[] nums = {3, 4, 6, 2, 1};
List<List<Integer>> permutations = Permutation.permute(nums);
for (List<Integer> permutation : permutations) {
    System.out.println(permutation);
}

输出:

[3, 4, 6, 2, 1]
[3, 4, 6, 1, 2]
[3, 4, 2, 6, 1]
[3, 4, 2, 1, 6]
[3, 4, 1, 6, 2]
[3, 4, 1, 2, 6]
[3, 2, 6, 4, 1]
[3, 2, 6, 1, 4]
[3, 2, 4, 6, 1]
[3, 2, 4, 1, 6]
[3, 2, 1, 6, 4]
[3, 2, 1, 4, 6]
[3, 6, 4, 2, 1]
[3, 6, 4, 1, 2]
[3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, 2, 4, 3, 1]
[6, 2, 4, 1, 3]
[6, 2, 1, 4, 3]
[6, 2, 1, 3, 4]
[6, 4, 2, 3, 1]
[6, 4, 2, 1, 3]
[6, 1, 2, 4, 3]
[6, 1, 2, 1, 4]
[6, 1, 4, 2, 3]
[6, 1, 4, 1, 3]
[6, 1, 3, 1, 4]
[6, 1, 3, 4, 1]
[4, 2, 6, 3, 1]
[4, 2, 6, 1, 3]
[4, 2, 1, 6, 3]
[4, 2, 1, 3, 6]
[4, 6, 2, 3, 1]

以上是如何使用递归方法生成唯一整数数组的所有可能排列?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn