0
点赞
收藏
分享

微信扫一扫

力扣 46. 全排列


46. 全排列

给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。

示例 1:

输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
示例 2:

输入:nums = [0,1]
输出:[[0,1],[1,0]]
示例 3:

输入:nums = [1]
输出:[[1]]

提示:

1 <= nums.length <= 6
-10 <= nums[i] <= 10
nums 中的所有整数 互不相同

class Solution {
    // 单个答案使用到的容器
    static List<Integer> list;
    // 所有答案使用到的容器
    static List<List<Integer>> allList;

    static boolean[] check;
    static int[] template;
    static int arrLen;

    public List<List<Integer>> permute(int[] nums) {
        template = nums;
        arrLen = nums.length;
        check = new boolean[nums.length];
        list = new LinkedList<>();
        allList = new ArrayList<>();
        dfs(0);
        return allList;
    }

    private static void dfs(int len) {
        if (len == arrLen) {
            // System.out.println(list);
            allList.add(new ArrayList<>(list));
        } else {
            // 未满足条件,继续递归
            for (int i = 0; i < template.length; i++) {
                if (!check[i]) {
                    list.add(template[i]);
                    check[i] = true;
                    dfs(len + 1);
                    list.remove(len);
                    check[i] = false;
                }
            }
        }
    }
}


举报

相关推荐

0 条评论