LeetCode 46 全排列 - Java 实现

1. 题目

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

  • 1 <= nums.length <= 6
  • 10 <= nums[i] <= 10
  • 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]]

2. 题解参考

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class LeetCode46_01_02 {

    List<List<Integer>> ret = new LinkedList<>();
    LinkedList<Integer> tempList = new LinkedList<>();


    public List<List<Integer>> permute(int[] nums) {
        // 定义一个与 nums 等长的数组,用于记录当前的值是否被使用
        // true 表示已被使用
        // false 表示未被使用
        boolean[] numState = new boolean[nums.length];
        backTracking(nums, numState);
        return ret;
    }

    public void backTracking(int[] nums, boolean[] numState) {
        // tempList 和 nums 长度相等表名所有元素都已经添加
        if (tempList.size() == nums.length) {
            ret.add(new ArrayList<>(tempList));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            // 如果元素已经被使用过,则直接进入下一轮循环
            if (numState[i]) {
                continue;
            }
            tempList.add(nums[i]);
            numState[i] = true;

            backTracking(nums, numState);

            numState[i] = false;
            tempList.removeLast();
        }
    }
}

3. 解题思路

这题的我主要考虑的难点是:

  • 如何判断这个元素是否使用过

最开始我使用的是列表存储没有被使用过的元素 LeetCode40_01_01 ,但是发现速度比较慢,之后替换成本文中使用数组记录每个元素使用状态的方法。

4. 代码下载

  1. Github (使用数组)algorithm-learning/LeetCode46_01_02.java at master · cc01cc/algorithm-learning: https://github.com/cc01cc/algorithm-learning/blob/master/practice/leetcode/LeetCode46_01_02.java
  2. Github (使用列表)algorithm-learning/LeetCode40_01_01.java at master · cc01cc/algorithm-learning: https://github.com/cc01cc/algorithm-learning/blob/master/practice/leetcode/LeetCode40_01_01.java
  3. (备用,非同步)城通网盘 algorithm-learning/LeetCode46_01_02.java: https://url57.ctfile.com/f/37032957-647606214-c731fa?p=9427 (访问密码: 9427)
  4. (备用,非同步)城通网盘 algorithm-learning/LeetCode46_01_01.java: https://url57.ctfile.com/f/37032957-647606212-33ecfa?p=9427 (访问密码: 9427)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

零一魔法

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值