【排列&字典序】Next Permutation

来源:互联网 发布:昆明网络推广哪家好 编辑:程序博客网 时间:2024/05/22 15:03

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.

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

解法:按字典序方法求出下一个排列,若已经是最后的顺序则将数组按升序排列

public class Solution {    public void reverse(int []num, int i){        int j = num.length - 1;        while(i < j){            int temp = num[i];            num[i] = num[j];            num[j] = temp;            i++;            j--;        }    }        public void nextPermutation(int[] num) {        int len = num.length;        if(len <= 1) return ;                int pos = len - 2;                while(pos >=0 && num[pos+1] <= num[pos]) pos--;                if(pos >= 0){            int i = len - 1;            while(num[i] <= num[pos]) i--;                        int temp = num[pos];            num[pos] = num[i];            num[i] = temp;                        if(pos+1 < len)            reverse(num, pos+1);        }        else{            Arrays.sort(num);        }    }}


0 0
原创粉丝点击