31. Next Permutation(解法)

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.spa

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).code

The replacement must be in-place, do not allocate extra memory.blog

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排序

這個題剛開始看我是懵的,由於之前沒接觸過全排序,不知道它要幹嗎,瞭解了全排序以後,其實就是交換數據,好比說須要交換第i和第j個元素(假設i<j),則交換完以後,第i+1及其以後的元素要進行重排序,使其遞增;那麼如今的問題就是找到要交換的元素,我所作就是從後往前查找:it

(1)好比如今要查倒數第k個元素,則從倒數第一個元素到倒數第k+1個元素進行順序查找,若找到其中有一個元素的值大於倒數第k個元素的值,則進行交換,並在交換後按照上述方法排序。io

(2)若後面元素的值都比倒數第k個值小(或相等),則倒數第k個元素到倒數第一個元素造成一個非嚴格遞減序列,則k--,繼續(1);class

代碼:方法

 1 class Solution {
 2 public:
 3 void nextPermutation(vector<int>& nums)
 4 {
 5     if (nums.size()!=0)
 6     {
 7         int n=0,size=nums.size();
 8         for(int i=size-2;i>=0;i--)
 9         {
10             int m=nums[i];
11             for(int j=size-1;j>i;j--)
12             {
13                 if (m<nums[j])
14                 {
15                     nums[i]=nums[j];
16                     nums[j]=m;
17                     n=1;
18                     break;
19                 }
20             }
21             if (n==1)
22             {
23                 sort(nums.begin()+i+1,nums.end());
24                 break;
25             }
26         }
27         if (n==0)
28         {
29             for(int i=0;i<size/2;i++)
30             {
31                 int m=nums[i];
32                 nums[i]=nums[size-i-1];
33                 nums[size-i-1]=m;
34             }
35         }
36     }
37 }
38 };
相關文章
相關標籤/搜索