字典排序全排列--坐标法

在前一篇文章中记录了字典排序的全排列算法,但是这有一个前提就是需要保证其中的元素是有序的,因此这篇文章记录改进的字典有序全排列算法,额外记录其中元素的下标,保证下标有序。相当于对下标进行全排列,然后对于生成的坐标序列取对应的元素值,构成一个元素序列。

P =    [9,8,7,1,2,3,4,...n]

pos = [0,1,2,3,4,....,..m]

pos记录p数组中元素的下标值,然后对pos所有元素进行全排列。

public static List<List<Integer>> premuteCoordinate(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> posList = new ArrayList<>();
        List<Integer> temp = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            // 记录坐标
            temp.add(nums[i]);
            posList.add(i);
        }
        result.add(new ArrayList<>(temp));

        while (true) {
            int len = nums.length - 1;
            int lowIndex = 0;
            int highIndex = 0;
            boolean hasFound = false;
            for (int i = len; i > 0; i--) {
                if (posList.get(i - 1) < posList.get(i)) {
                    lowIndex = i - 1;
                    hasFound = true;
                    break;
                }
            }
            if (!hasFound) {
                break;
            }
            for (int j = len; j > lowIndex; j--) {
                if (posList.get(j) > posList.get(lowIndex)) {
                    highIndex = j;
                    break;
                }
            }
            // 交换下标
            int t = posList.get(lowIndex);
            posList.set(lowIndex, posList.get(highIndex));
            posList.set(highIndex, t);
            // 翻转
            for (int k = lowIndex + 1; k <= len; k++, len--) {
                    int l = posList.get(k);
                    posList.set(k, posList.get(len));
                    posList.set(len, l);
            }
            List<Integer> test = new ArrayList<>();
            for (int key : posList) {
                test.add(nums[key]);
            }
            result.add(test);

        }
        return result;
    }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值