[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/problems/next-permutation/

思路:如下图。

该算法理解:

步骤1从右向左遍历,如果一直是递增序列,则已经是当前子串的最后一个排列(极限情况全部递增,则代表是全串的最后一个排列),所以1步骤中需要寻找第一个递减元素,即partitionNumber。此时的排列是以partitionNumber开头的最大的排列(因为后面都递减)。

步骤2中从右向左找第一个比partitionNumber大的元素,作为新的稍微大一点的排列的头,所以两者交换位置,并且后面的元素要reverse变成以新partitionNumber为头的最小排列。

 


第二遍记录:
严格按照算法来即可。
  注意比较的时候是否有等号
  注意最后一个排列的特殊情况,partitionIdx==-1。

 

import java.util.Arrays;

public class Solution {
    public void nextPermutation(int[] num) {
        if (num == null || num.length <= 1)
            return;
        int partitionIdx = -1;
        for (int i = num.length - 2; i >= 0; i--) {

            if (num[i] < num[i + 1]) {
                partitionIdx = i;
                break;
            }
        }
        if (partitionIdx == -1) {
            reverse(num, 0, num.length - 1);
            return;
        }

        int changeNumIdx = -1;
        for (int i = num.length - 1; i >= 0; i--) {

            if (num[i] > num[partitionIdx]) {
                changeNumIdx = i;
                break;
            }
        }
        int tmp = num[partitionIdx];
        num[partitionIdx] = num[changeNumIdx];
        num[changeNumIdx] = tmp;

        reverse(num, partitionIdx + 1, num.length - 1);

    }

    private void reverse(int[] a, int from, int to) {
        int i = from;
        int j = to;
        while (i < j) {
            int tmp = a[i];
            a[i] = a[j];
            a[j] = tmp;
            i++;
            j--;
        }
    }

    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, 2, 3 };
        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

 

 

posted @ 2014-06-26 19:41  jdflyfly  阅读(201)  评论(0编辑  收藏  举报