31. 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 and use only constant 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

一開始無從下手,因為不理解題目要干啥。然后查資料:

next_permutation函數將按字母表順序生成給定序列的下一個較大的排列,直到整個序列為降序為止。prev_permutation函數與之相反,是生成給定序列的上一個較小的排列。二者原理相同,僅遍例順序相反

 

 

 

 

 

問題:如何求一個數組的下一個排列?

 

 

 

假設該數組為3 6 4 2.下一個排列應為 4 2 3 6.

 

過程:對於一個任意序列,最小的排列是增序,最大的為減序。

 

從最后一位向前看,首先得到的是2,單純的一個數不需要進行交換。

 

然后得到的是 4 2,4大於2,在這個子序列中已經為最大序列,無法排出更大的序列了。

 

然后得到的是 6 4 2,原理同上。

 

之后得到的是 3 6 4 2,此時由於3小於6且小於4,而 3 6 4 2的下一個排列應為比3 6 4 2這個排列大的排列中最小的那個,所以3應該和4進行交換,此時該排列變為 4 6 3 2.此時4位於首端,所以之后的序列應為最小序列,即 2 3 6.綜上,最終結果應為 4 2 3 6.

--------------------- 

作者:HyJoker 

來源:CSDN 

原文:https://blog.csdn.net/hyjoker/article/details/50899362 

版權聲明:本文為博主原創文章,轉載請附上博文鏈接!

好的,現在已經有點明白了。

至此,可以寫code了

 

class Solution {
    public void nextPermutation(int[] nums) {
        if(nums==null || nums.length==0) return;
        int i = nums.length-2;
        while(i>=0&&nums[i] >= nums[i+1])
            i--;
        if(i>=0){
        int j = i + 1;
        while(j < nums.length && nums[j] > nums[i])
            j++;
        j--;
        swap(nums,i,j);       
        }
         reverse(nums,i+1,nums.length-1);
    }
    public void swap(int[] nums, int i, int j){
        int t = nums[i];
        nums[i] = nums[j];
        nums[j] = t;
    }
    public void reverse(int[] nums, int i, int j){
        while(i<j){
            swap(nums, i++, j--);
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM