46. 全排列
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
思想
采用DFS回溯,定义track数组用于记录当前尝试的序列,用二维数组res保存通过的排列;
我们总是循环尝试将当前数组nums中还未访问的元素nums[i]加入track中,然后进行下一层深度搜索dfs,如果不符合则从track中去除该结点nums[i]
代码
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new LinkedList<>();
LinkedList<Integer> track = new LinkedList<>();
int len = nums.length;
if(len == 0){
return res;
}
dfs(nums, track, res);
return res;
}
public void dfs(int[] nums, LinkedList<Integer> track, List<List<Integer>> res) {
if(track.size() == nums.length){
res.add(new LinkedList(track));
}
for(int i = 0; i < nums.length; i++){
if(track.contains(nums[i])){
continue;
}
track.add(nums[i]);
dfs(nums, track, res);
track.removeLast();
}
}
}