给定一个 没有重复 数字的序列,返回其所有可能的全排列。

示例:输入: [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

【回溯】

public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        List<Integer> res = new ArrayList<>();
        for (int num : nums) {
            res.add(num);
        }
        swap(res, ans, nums.length, 0);
        return ans;
    }

    private void swap(List<Integer>res, List<List<Integer>>ans, int len, int index){
        if (index == len){
            ans.add(new ArrayList<>(res));
            return;
        }
        for(int i = index; i < len; i++){
            Collections.swap(res, index, i);
            swap(res, ans, len, index+1);
            Collections.swap(res, index, i);
        }
    }

 


版权声明:本文为qq_39380838原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_39380838/article/details/108704639