题目描述

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

示例:

输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]

回溯

注意 在添加到res时 要进行复制 防止因为值传递导致之后生成的结果每次都是空

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if(nums.length <1 || nums ==null) return res;
        boolean[] used = new boolean[nums.length];
        List<Integer> temp = new ArrayList<>();
        backtrack(res,nums,temp,used);
        return res;
    }

    public void backtrack(List<List<Integer>> res, int[] nums, List<Integer> temp, boolean[] used) {
        if (temp.size() == nums.length) {
            //这里要复制一份 防止值传递
            res.add(new ArrayList<Integer>(temp));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if(!used[i]){
                temp.add(nums[i]);
                used[i] = true;
                backtrack(res, nums, temp, used);
                temp.remove(temp.size() - 1);
                used[i] = false;
            }

        }
    }
}


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