参考链接:https://leetcode-cn.com/problems/permutations-ii/solution/hui-su-suan-fa-python-dai-ma-java-dai-ma-by-liwe-2/
1.全排列
题目描述
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
思路
参考链接
https://leetcode-cn.com/problems/permutations/solution/hui-su-suan-fa-python-dai-ma-java-dai-ma-by-liweiw/
整个流程类似于一个棵决策树的遍历,采用深度优先搜索策略。在实现的时候主要有两点需要注意
- 使用used[len]数组,来保存已经访问过的数值
- 在返回当前层函数之前,记得回退,撤销当前path和used的访问信息。
List<List<Integer>> res; // 记录path的集合
public List<List<Integer>> permute(int[] nums) {
// 空值处理
if(nums.length==0)
return new ArrayList<>();
int len = nums.length;
res = new ArrayList<>();
List<Integer> path = new ArrayList<Integer>();
boolean[] used = new boolean[len]; // 记录是否访问过
dfs(nums, len, 0, path, used);
return res;
}
public void dfs(int[] nums, int len, int depth, List<Integer> path, boolean[] used){
if(depth==len)
res.add(new ArrayList<Integer>(path)); // 拷贝一个对象添加到res集合中
// 搜索数组中访问的数值
for(int i=0; i<