给定一个 没有重复 数字的序列,返回其所有可能的全排列。
示例:
输入: [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
思路:
可以采用BFS也可以采用DFS
DFS主要还是回溯的思想,满足条件的就记录并回溯,没到最后一层depth就继续往下,
注意退出的条件和是否已经判断过回溯条件的重置
class Solution {public static List<List<Integer>> permute(int[] nums) {List<List<Integer>> res = new LinkedList();if (nums.length == 0){return res;}int n = nums.length;Deque<Integer> path = new ArrayDeque<Integer>();boolean [] used = new boolean[nums.length];dfs(nums,0,path,used,res);return res;}private static void dfs(int[] nums, int depth, Deque<Integer> path, boolean[] used, List<List<Integer>> res) {//如果全部都判断完了就记录并返回if (depth == nums.length){res.add(new ArrayList<>(path));return;}for (int i = 0; i < nums.length; i++) {if (used[i]){continue;}path.add(nums[i]);used[i] = true;dfs(nums,depth + 1,path,used,res);//返回上一层的同时条件给他初始化回去path.remove(nums[i]);used[i] = false;}}}
官方答案:
class Solution {public void backtrack(int n,ArrayList<Integer> output,List<List<Integer>> res,int first) {// 所有数都填完了if (first == n)res.add(new ArrayList<Integer>(output));for (int i = first; i < n; i++) {// 动态维护数组Collections.swap(output, first, i);// 继续递归填下一个数backtrack(n, output, res, first + 1);// 撤销操作Collections.swap(output, first, i);}}public List<List<Integer>> permute(int[] nums) {List<List<Integer>> res = new LinkedList();ArrayList<Integer> output = new ArrayList<Integer>();for (int num : nums)output.add(num);int n = nums.length;backtrack(n, output, res, 0);return res;}}
