温馨提示×

java全排列算法怎么实现

小亿
102
2023-09-25 22:48:50
栏目: 编程语言

以下是一种实现Java全排列算法的方法:

import java.util.ArrayList;
import java.util.List;
public class Permutation {
public static void main(String[] args) {
int[] nums = {1, 2, 3};
List<List<Integer>> permutations = permute(nums);
System.out.println(permutations);
}
public static List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
backtrack(result, new ArrayList<>(), nums);
return result;
}
private static void backtrack(List<List<Integer>> result, List<Integer> tempList, int[] nums) {
if (tempList.size() == nums.length) {
result.add(new ArrayList<>(tempList));
} else {
for (int i = 0; i < nums.length; i++) {
if (tempList.contains(nums[i])) {
continue; // 跳过已经添加过的数字
}
tempList.add(nums[i]);
backtrack(result, tempList, nums); // 递归调用
tempList.remove(tempList.size() - 1); // 回溯
}
}
}
}

在这个实现中,我们使用了回溯算法来生成全排列。我们定义了一个backtrack方法来生成所有可能的排列。在每一步中,我们将一个数字添加到临时的排列中,在递归调用后,我们将该数字从临时排列中移除,以便进行下一次尝试。当临时排列的长度等于输入数组的长度时,我们将其添加到结果列表中。

上述代码的输出结果为[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]],即为输入数组[1, 2, 3]的所有全排列。

0