46. Permutations

本文介绍了一种使用递归算法解决全排列问题的方法。通过给出的代码示例,详细解释了如何对给定的整数集合生成所有可能的排列组合。文章提供了完整的Java实现,包括递归函数和交换元素的辅助函数。

摘要生成于 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]
]

难度:medium

题目:给定一组集合元素,返回其所有排列数。

思路:递归

Runtime: 3 ms, faster than 70.98% of Java online submissions for Permutations.
Memory Usage: 28 MB, less than 4.36% of Java online submissions for Permutations.

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        permute(nums, 0, new Stack<Integer>(), result);
        
        return result;
    }
    
    private void permute(int[] nums, int idx, Stack<Integer> stack, List<List<Integer>> result) {
        if (idx == nums.length) {
            result.add(new ArrayList<>(stack));
            return;
        }
        
        for (int i = idx; i < nums.length; i++) {
            stack.push(nums[i]);
            swap(nums, i, idx);
            permute(nums, idx + 1, stack, result);
            swap(nums, i, idx);
            stack.pop();
        }
    }

    private void swap(int[] nums, int i, int j) {
        int t = nums[i];
        nums[i] = nums[j];
        nums[j] = t;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值