这是我参与2022首次更文挑战的第13天,活动详情查看:2022首次更文挑战
给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
我只能说很经典,十分的经典,但是这道题的确很关键,我有很多的学长在面试的过程中经常性的被问这道题
首先,我们需要知道什么是全排列
从n个不同元素中任取m(m≤n)个元素,按照一定的顺序排列起来,叫做从n个不同元素中取出m个元素的一个排列。当m=n时所有的排列情况叫全排列。
那我们需要怎么做呢?
我们慢慢的确定,当它满的时候我们返回上一个阶段,如果我们这个阶段的返回也已经选择完毕,我们再向上返回,直至我们最顶端的所有选择都选择完毕,这就是我们的回溯法
如果有不了解回溯的可以看一下我这一篇文章
我们没有使用插入的方式,使用时交换的方式,但是原理是一样的,
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> output = new ArrayList<Integer>();
for (int num : nums){
output.add(num);
}
int n = nums.length;
reList(n,output,result,0);
return result;
}
public void reList(int n,List<Integer> output,List<List<Integer>> result,int first){
//我们在这里判断是否遍历到最底部,
if(first == n){
//到最底部的时候将序列添加入数组
result.add(new ArrayList<Integer>(output));
}
//向下层循环遍历
//first和i代表我们需要交换的两个数
//first还代表我们处于第几层
for (int i = first; i < n; i++) {
Collections.swap(output,first,i);
//向下一层遍历
reList(n,output,result,first+1);
//下面遍历完成之后,我们需要将数组返回原状态
Collections.swap(output,first,i);
}
}
}