LeetCode 46 Permutations

博客围绕LeetCode上给定不同整数集合求所有排列组合的问题展开。提出用回溯法解题,将问题转化为求排列组合树中从根节点到空节点的所有路径。在实现时,要处理边状态冲突,注意深拷贝,还可用辅助数组记录数字可选状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

Given a collection of distinct integers, return all possible permutations.

Example:
Input: [1,2,3]
Output:

[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

解法思路(一)

  • 排列组合的问题;
  • 回溯法;
  • 当给出输入的数组,代表整个排列组合的树就已经形成了,如下:

    
8195388-b5c55682be57510c.png
算法过程.png
  • 问题转换成了,求这棵树中,所有从根节点到空节点的路径;

解法实现(一)

关键字

回溯 递归 树的路径

实现细节
  • 由于树上每一层的边是有冲突的,上层的边用过的数字,下层的边就不能再用了,所以在回溯的过程中,要将边的状态置为可用;
  • 已经确定的排列组合在往 res 中放的时候,要注意是深拷贝,否则递归过程中找到的组合保存不下来;
  • 用一个辅助数组 used 记录每个数字是否可选的状态;
package leetcode._46;

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

public class Solution46_1 {

    private List<List<Integer>> res;
    private boolean[] used;

    public List<List<Integer>> permute(int[] nums) {

        res = new ArrayList<List<Integer>>();
        if (nums == null || nums.length == 0) {
            return res;
        }

        used = new boolean[nums.length];
        LinkedList<Integer> combination = new LinkedList<>();

        findCombination(nums, 0, combination);

        return res;
    }

    private void findCombination(int[] nums, int index, LinkedList<Integer> combination) {

        if (index == nums.length) {
            res.add((List<Integer>)combination.clone());
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (!used[i]) {
                combination.addLast(nums[i]);
                used[i] = true;
                findCombination(nums, index + 1, combination);
                combination.removeLast();
                used[i] = false;
            }
        }

        return;
    }

}

返回 LeetCode [Java] 目录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值