给定一个 没有重复 数字的序列,返回其所有可能的全排列。
    示例:
    输入: [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就继续往下,
    注意退出的条件和是否已经判断过回溯条件的重置

    1. class Solution {
    2. public static List<List<Integer>> permute(int[] nums) {
    3. List<List<Integer>> res = new LinkedList();
    4. if (nums.length == 0){
    5. return res;
    6. }
    7. int n = nums.length;
    8. Deque<Integer> path = new ArrayDeque<Integer>();
    9. boolean [] used = new boolean[nums.length];
    10. dfs(nums,0,path,used,res);
    11. return res;
    12. }
    13. private static void dfs(int[] nums, int depth, Deque<Integer> path, boolean[] used, List<List<Integer>> res) {
    14. //如果全部都判断完了就记录并返回
    15. if (depth == nums.length){
    16. res.add(new ArrayList<>(path));
    17. return;
    18. }
    19. for (int i = 0; i < nums.length; i++) {
    20. if (used[i]){
    21. continue;
    22. }
    23. path.add(nums[i]);
    24. used[i] = true;
    25. dfs(nums,depth + 1,path,used,res);
    26. //返回上一层的同时条件给他初始化回去
    27. path.remove(nums[i]);
    28. used[i] = false;
    29. }
    30. }
    31. }

    官方答案:

    1. class Solution {
    2. public void backtrack(int n,ArrayList<Integer> output,List<List<Integer>> res,int first) {
    3. // 所有数都填完了
    4. if (first == n)
    5. res.add(new ArrayList<Integer>(output));
    6. for (int i = first; i < n; i++) {
    7. // 动态维护数组
    8. Collections.swap(output, first, i);
    9. // 继续递归填下一个数
    10. backtrack(n, output, res, first + 1);
    11. // 撤销操作
    12. Collections.swap(output, first, i);
    13. }
    14. }
    15. public List<List<Integer>> permute(int[] nums) {
    16. List<List<Integer>> res = new LinkedList();
    17. ArrayList<Integer> output = new ArrayList<Integer>();
    18. for (int num : nums)
    19. output.add(num);
    20. int n = nums.length;
    21. backtrack(n, output, res, 0);
    22. return res;
    23. }
    24. }