要实现全排列的递归算法,可以按照以下步骤进行:
以下是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]
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: Java归一化处理的方法是什么