题目:
链接:https://leetcode-cn.com/problems/permutations/
思路:
- 这是一道典型的回溯算法题,需要注意的是全排列是有顺序之分的,123和132是两个结果
- 基本思路就是深度优先遍历,每次固定一个元素(添加至temp中),并保存当前元素已经被使用used,然后在剩下的元素中继续固定,当递归深度depth和全排列长度相等时,保存一下中间数组temp的值,这里需要注意temp是引用,需要复制数组
- 然后向上回溯一层,即回退temp的最后一个值,找找有没有别的没用的值,因为固定了1之后,23和32是两次回溯到1之后的结果
- 重复上面的操作,直到一直回溯到最顶层(空数组)
代码:
import java.util.ArrayList;
class Solution {
public List<List<Integer>> permute(int[] nums) {
int len = nums.length;
List<List<Integer>> result = new ArrayList<>();
if(len==0) return result;
List<Integer> temp = new ArrayList<>();
boolean[] used = new boolean[len];
dfs(nums, len, 0, temp, result, used);
return result;
}
public void dfs(int[] nums, int len, int depth, List<Integer> temp, List<List<Integer>> result, boolean[] used){
if(depth==len){
result.add(new ArrayList<>(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);
}
}
}