This is a typical backtracking algorithm problem. It should be noted that the whole arrangement is in order. 123 and 132 are two results.
The basic idea is depth-first traversal, fix one element at a time (added to temp), and save the current element has been used, and then continue to fix in the remaining elements, when the recursion depth depth and the full arrangement length are equal, save Let’s look at the value of the middle array temp. Here you need to note that temp is a reference and the array needs to be copied
Then go back one level, that is, go back to the last value of temp, and look for other useless values, because after fixing 1, 23 and 32 are the results of backtracking to 1 twice
Repeat the above operation until you have all the way back to the top (empty array)
Code:
import java.util.ArrayList;classSolution{
public List<List<Integer>>permute(int[] nums){
int len = nums.length;
List<List<Integer>> result =newArrayList<>();if(len==0)return result;// 保存排列的中间结果
List<Integer> temp =newArrayList<>();// 开关数组,记录此次排列的当前元素是否被使用boolean[] used =newboolean[len];dfs(nums, len,0, temp, result, used);return result;}publicvoiddfs(int[] nums,int len,int depth, List<Integer> temp, List<List<Integer>> result,boolean[] used){
// 出现全排列,保存此时temp的结果if(depth==len){
result.add(newArrayList<>(temp));return;}for(int i=0;i<len;i++){
// 该元素已经使用过if(used[i]){
continue;}// 记录状态值
used[i]=true;
temp.add(nums[i]);// 深度优先遍历,直到找到一个全排列dfs(nums,len,depth+1,temp,result,used);// 回溯,逆操作状态值
used[i]=false;
temp.remove(temp.size()-1);}}}