If you do it with DFS, it is inefficient. Here's a way to do this: to find the next sequence, start by looking for the longest increment array from the tail, if it is incremented from the end of the tail, this is the maximum sequence, and the next sequence is to flip the maximum sequence. If no increment array exists, the last two digits are exchanged. In other cases, record the previous digit of the incrementing array and find the smallest number in the increment array that is larger than this number, swap two number positions, then flip the incrementing array, and the result is the next sequence. Relevant certifications can be found online.
1 classSolution {2 Public:3 voidNextpermutation (vector<int>&nums) {4 if(Nums.size () <=1)5 return;6 intI=nums.size ()-1;7 while(i>=1&&nums[i-1]>=Nums[i])8 {9i--;Ten } One if(i==0) A { - Reverse (Nums.begin (), Nums.end ()); - } the Else if(I==nums.size ()-1) - { -Swap (nums[i],nums[i-1]); - } + Else - { +i--; A intJ; at for(J=nums.size ()-1; j>=i;j--) - { - if(nums[j]>Nums[i]) - Break; - } - swap (nums[i],nums[j]); inReverse (Nums.begin () +i+1, Nums.end ()); - } to } +};
View Code
If the previous sequence is required, the longest descending array is found. Other analyses are similar.
1 classSolution {2 Public:3 voidPrevpermutation (vector<int>&nums) {4 if(Nums.size () <=1)5 return;6 intI=nums.size ()-1;7 while(i>=1&&nums[i-1]<=Nums[i])8 {9i--;Ten } One if(i==0) A { - Reverse (Nums.begin (), Nums.end ()); - } the Else if(I==nums.size ()-1) - { -Swap (nums[i],nums[i-1]); - } + Else - { +i--; A intJ; at for(J=nums.size ()-1; j>=i;j--) - { - if(nums[j]<Nums[i]) - Break; - } - swap (nums[i],nums[j]); inReverse (Nums.begin () +i+1, Nums.end ()); - } to } +};
View Code
LC31 Next permutation