LeetCode 46 Permutations (全排列)

本文详细介绍了一种求解全排列问题的高效算法,并通过具体实例解释了如何找出所有可能的排列组合。文章首先介绍了算法的基本步骤,包括寻找最后一个升序序列的末尾、找到可以与之交换的元素等关键操作,并提供了完整的Java实现代码。

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

For example,
[1,2,3] have the following permutations:

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


题目链接:https://leetcode.com/problems/permutations/

题目大意:求全排列

题目分析:求全排列的算法分为以下几步

1. 找最后一个升序的末尾位置pos1

2. 找在pos1 - 1后的最后一个大于它的数字位置pos2

3. 交换pos1 - 1和pos2位置的数

4. 对pos1及之后的数字从小到大排序

例如 1 5 2 4 3,pos1 = 3,pos2 = 4交换得1 5 3 4 2,pos1后排序得1 5 3 2 4

public class Solution {
    
    void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
    
    boolean nextPermutation(int[] nums, int len) {
        int pos1 = -1, pos2 = 0;
        for(int i = len - 1; i >= 1; i--) {
            if(nums[i] > nums[i - 1]) {
                pos1 = i;
                break;
            }
        }
        if(pos1 == -1) {
            return false;
        }
        for(int i = len - 1; i >= pos1; i--) {
            if(nums[i] > nums[pos1 - 1]) {
                pos2 = i;
                break;
            }
        }
        swap(nums, pos1 - 1, pos2);
        Arrays.sort(nums, pos1, len);
        return true;
    }
    
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        List<Integer> currentList;
        Arrays.sort(nums);
        int cnt = 0;
        int len = nums.length;
        do {
            currentList = new ArrayList<>();
            for(int i = 0; i < len; i++)
                currentList.add(nums[i]);
            ans.add(currentList);
        }while(nextPermutation(nums, len));
        return ans;
    }
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值