leetcode 第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]]

思路

有一堆数字,找它的全排列,就是把所有的数字都用上,依次获取数字。第一个数字选择k,然后对剩下的数字做全排列。这样,我们就找到了子问题,这个问题可以通过子问题的递归来解决。递归结束条件就是已经选了所有的数字。

这里最大的一个问题其实就是已经选过的数字和没选过的数字怎么区分。有一个方法就是用标记记录,在递归回溯的时候还原标记即可。另一种方法是把已经选过的数字和没选过的数字分成左右两部分,每选择一个数字就将它放到左侧,获取数字的时候始终是从右侧获取。

代码

下面是自己写的代码,用stack记录过程中选择的数字;将选过的数字替换到数组的左侧,回溯的时候再替换回去。

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

class Solution {
    List<List<Integer>> result = new ArrayList<>();
    public List<List<Integer>> permute(int[] nums) {
        Stack<Integer> stack = new Stack<>();
        dfs(nums, 0, stack);
        return result;
    }

    public void dfs(int[] nums, int index, Stack<Integer> stack) {
        if (index == nums.length) {
            result.add(new ArrayList<>(stack));
        } else {
            for (int i = index; i < nums.length; i++) {
                swap(nums, index, i);
                stack.push(nums[index]);
                dfs(nums, index + 1, stack);
                stack.pop();
                swap(nums, index, i);
            }
        }
    }

    public void swap(int[] nums, int indexA, int indexB) {
        int temp = nums[indexA];
        nums[indexA] = nums[indexB];
        nums[indexB] = temp;
    }
}

官方代码:
有两个技巧值得学习:

  1. 选择数字的过程直接也作为了结果
  2. 用List去保存中间结果,既可以在最终直接作为new ArrayList的参数copy,又可以使用Collections.swap进行方便的数字交换。
class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();

        List<Integer> output = new ArrayList<Integer>();
        for (int num : nums) {
            output.add(num);
        }

        int n = nums.length;
        backtrack(n, output, res, 0);
        return res;
    }

    public void backtrack(int n, List<Integer> output, List<List<Integer>> res, int first) {
        // 所有数都填完了
        if (first == n) {
            res.add(new ArrayList<Integer>(output));
        }
        for (int i = first; i < n; i++) {
            // 动态维护数组
            Collections.swap(output, first, i);
            // 继续递归填下一个数
            backtrack(n, output, res, first + 1);
            // 撤销操作
            Collections.swap(output, first, i);
        }
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/permutations/solution/quan-pai-lie-by-leetcode-solution-2/
来源:力扣(LeetCode

复杂度

时间复杂度:O(N * N!)
空间复杂度:O(N)

耗时

50分钟

扩展

关于回溯,有一些题目可以集中练习一下。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值