算法时间复杂度为 n!
使用回溯算法实现
//全排列
static LinkedList<LinkedList<Integer>> res = new LinkedList<>();
public void solution1(int[] nums, LinkedList<Integer> hasSel){
if (hasSel.size() == nums.length){//全排列结束,选3个数字
res.add(new LinkedList<>(hasSel));
return ;
}
for (int i = 0; i < nums.length; i++) {
if (hasSel.contains(nums[i])) continue;//排除已经选过的
hasSel.add(nums[i]);//做选择
solution1(nums, hasSel);//进入下一个决策树
hasSel.removeLast();//回溯,取消选择
}
}
使用交换算法实现
public void solution2(int[] nums, int start, int end){
if (start == end){
for (int i:nums
) {
System.out.print(i + " ");
}
System.out.println();
return ;
}
for (int i = start; i <= end; i++) {
swap(nums, i,start);
solution2(nums, start + 1, end);
swap(nums, i, start);
}
}
public void swap(int[] nums, int i, int start) {
int temp = nums[i];
nums[i] = nums[start];
nums[start] = temp;
}