LeetCode 46. Permutations

LeetCode 46. Permutations (全排列)

题目

链接

https://leetcode-cn.com/problems/permutations/

问题描述

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

示例

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

提示

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

思路

回溯法,以每一个数为开头,然后进行处理,如果重复就跳过,等排列完毕就存储答案。

复杂度分析

时间复杂度 O(n n!)
空间复杂度 O(n)

代码

Java

    List<List<Integer>> res = new LinkedList<>();


    List<List<Integer>> permute(int[] nums) {
        LinkedList<Integer> track = new LinkedList<>();
        backtrack(nums, track);
        return res;
    }

    void backtrack(int[] nums, LinkedList<Integer> track) {

        if (track.size() == nums.length) {
            res.add(new LinkedList(track));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (track.contains(nums[i])) {
                continue;
            }
            track.add(nums[i]);
            backtrack(nums, track);
            track.removeLast();
        }
    }
posted @ 2022-04-10 16:15  cheng102e  阅读(20)  评论(0编辑  收藏  举报