首页 > 代码库 > [leetcode] Next Permutation

[leetcode] 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, 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

https://oj.leetcode.com/submissions/detail/2805266/

思路:如下图。

 

代码实现:

import java.util.Arrays;public class Solution {    public void nextPermutation(int[] num) {        if (num == null || num.length <= 1)            return;        int n = num.length;        int partitionIdx = -1;        for (int i = n - 1; i > 0; i--) {            if (num[i - 1] < num[i]) {                partitionIdx = i - 1;                break;            }        }        int tmp;        if (partitionIdx == -1) {            for (int i = 0, j = n - 1; i < j; i++, j--) {                tmp = num[i];                num[i] = num[j];                num[j] = tmp;            }        } else {            int changeNumIdx = -1;            for (int i = n - 1; i > partitionIdx; i--) {                if (num[i] > num[partitionIdx]) {                    changeNumIdx = i;                    break;                }            }            tmp = num[partitionIdx];            num[partitionIdx] = num[changeNumIdx];            num[changeNumIdx] = tmp;            for (int i = partitionIdx + 1, j = n - 1; i < j; i++, j--) {                tmp = num[i];                num[i] = num[j];                num[j] = tmp;            }        }    }    public static void main(String[] args) {        int[] num;        num = new int[] { 1, 2, 3, 5, 4, 4, 1 };        new Solution().nextPermutation(num);        System.out.println(Arrays.toString(num));        num = new int[] { 1, 1, 5 };        new Solution().nextPermutation(num);        System.out.println(Arrays.toString(num));        num = new int[] { 3, 2, 1 };        new Solution().nextPermutation(num);        System.out.println(Arrays.toString(num));        num = new int[] { 1, 1 };        new Solution().nextPermutation(num);        System.out.println(Arrays.toString(num));    }}

参考:

http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html

扩展:

http://blog.csdn.net/m6830098/article/details/17291259