[leetcode] next permutation

来源:互联网 发布:mac brew lamp 编辑:程序博客网 时间:2024/06/07 00:17

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, do not allocate extra memory.

思路:举例来说,5,6,7,10,8,2,1

首先从后往前遍历,寻找最后升序的地方,7->10, 是上升的。因为找下一个全排列,因为总体是升序的,所以寻找最后一个升序的位置,保证这个位置以前不做变动,但若从头至尾都是倒序,如 10,8,7,6,5,2,1,此时必须reverse整个array。

找到最后一个升序位置以后,我们只需关注此后的数,7,10,8,2,1 ,其中10以后必然降序(因为7,10是最后一个升序),此时我们需要找到这个子数组的下一个全排列,我们只需从10,8,2,1中从后往前遍历寻找第一个比7大的数字,并跟7swap一下,得到,8,10,7,2,1。但此时,我们需要的时8在该位置的第一个全排列,所以最后几位必须是升序的,所以把10,7,2,1再反序一下,得到8,1,2,7,10,得到结果。

public class Solution {    public void nextPermutation(int[] num) {        if (num == null) {            return;        }                int len = num.length;        for (int i = len - 2; i >= 0; i--) {            if (num[i + 1] > num[i]) {                int j;                for (j = len - 1; j > i - 1; j--) {                    if (num[j] > num[i]) {                        break;                    }                }                swap(num, i, j);                reverse(num, i + 1, len-1);                return;            }        }        reverse(num, 0, len-1);    }    void swap(int[] num, int i, int j) {        int tmp = num[i];        num[i] = num[j];        num[j] = tmp;    }    void reverse(int[] num, int beg, int end) {        for (int i = beg, j = end; i < j; i ++, j --) {            swap(num, i, j);        }    }}


0 0
原创粉丝点击