[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.

思路:舉例來說,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);
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章