这里是引用
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/permutations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
官方的视频题解
很详细,也很好理解
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
int len = nums.length;
if(len==0) return res;
Deque<Integer> path = new ArrayDeque<>();//栈保存路径
boolean[] used = new boolean[len];//是否使用过
dfs(nums,len,0,path,used,res);
return res;
}
/**
*@param nums 数组
*@param len 数组长度
*@param depth 递归的深度
*@param path 递归的路径
*@param used 是否已使用过
*@param res 结果
**/
private void dfs(int[] nums,int len,int depth,Deque<Integer> path,boolean[] used,List<List<Integer>> res){
if(depth==len){
res.add(new ArrayList(path));
return;
}
for(int i=0;i<len;i++){
if(used[i]) continue;
path.addLast(nums[i]);
used[i]=true;
dfs(nums,len,depth+1,path,used,res);
path.removeLast();
used[i]=false;
}
}
}
本文深入解析了全排列算法,通过示例展示了如何生成一个没有重复数字的序列的所有可能全排列。提供了详细的代码实现,包括递归深度优先搜索(DFS)算法,并解释了路径保存和已使用元素标记的概念。
3958

被折叠的 条评论
为什么被折叠?



