【Leetcode】31. Next Permutation 解题报告

【Leetcode】31. Next Permutation 解题报告

题面

https://leetcode.com/problems/next-permutation/
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place and use only constant extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

思路:

通过画一个树形图可以发现,每一次如果在下面找不到比自己的节点,说明要跨届了,就是往上一层。如果找到比自己大的,就需要将这个比自己大的当作第一个节点,然后剩下的节点排序。

第一遍(虽然做出来了正确的结果,但是实际上没有完全想明白)‘

class Solution {
    public void nextPermutation(int[] nums) {
        Integer[] numbers = new Integer[nums.length+1];
        numbers[0] = Integer.MAX_VALUE;
        for (int i = 1; i < nums.length + 1; i++) {
            numbers[i] = nums[i-1];
        }

        int start = numbers.length - 2;
        while (start >= 0) {
            int index = heleperFinding(numbers, start);
            if (index != -1) {
                int temp = numbers[index];
                numbers[index] = numbers[start];
                numbers[start] = temp;
                numbers = helperSorting(numbers, start+1);
                break;
            } else {
                start--;
            }
        }
        
        for (int i = 0; i < nums.length; i++) {
            nums[i] = numbers[i+1];
        }

        System.out.print("ending");
    }

    public Integer[] helperSorting(Integer[] numbers, int start) {
        Arrays.sort(numbers,start,numbers.length);
        return numbers;
    }

    public int heleperFinding(Integer[] nums, int index) {
        Arrays.sort(nums,index+1, nums.length);
        for (int i = index+1; i < nums.length; i++) {
            if (nums[i] > nums[index]) {
                return i;
            }
        }
        return -1;
    }
}

这道题应该需要用到backtracking? 怎么用?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值