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).spa
The replacement must be in-place, do not allocate extra memory.code
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
blog
思路:it
一個數最大的時候,它的各個位從左向右應該是從大到小的。咱們找到nums數組末尾從大到小的一段,記錄下該段的第一個元素的位置st。io
好比[0, 2, 4, 5, 2, 1], 末尾從大到小的一段是[4, 2, 1],st是3。咱們將該段的元素反轉,而後將st-1位置的元素與該段中第一個大於它的元素交換位置(若st爲0則不用交換)。這裏st-1位置的元素是4,該段中第一個大於它的值爲5。因此最後結果是[0, 2, 5, 1, 2, 4]。class
1 class Solution { 2 public: 3 void nextPermutation(vector<int>& nums) { 4 if (nums.size() == 0) return; 5 int st = nums.size() - 1; 6 while (st > 0 && nums[st - 1] >= nums[st]) st--; 7 std::reverse(nums.begin() + st, nums.end()); 8 if (st == 0) return; 9 auto it = std::upper_bound(nums.begin() + st, nums.end(), nums[st - 1]); 10 std::swap(nums[st - 1], *it); 11 } 12 };