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.
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | class Solution { public : void nextPermutation(vector< int >& nums) { int len = nums.size(); if (len <= 1) return ; int last = INT_MIN, l_i = 0, b_i = 0; int i; for (i = len - 1; i >= 0; --i){ if ( last <= nums[i]){ last = nums[i]; l_i = i; } else { break ; } } // if i is -1, then reverse the whole vector if (i == -1){ reverse(nums, 0, nums.size()); return ; } // find the first element bigger than the target element for (i = len-1; i >= 0; --i){ if (nums[i] > nums[l_i-1]){ b_i = i; break ; } } swap(nums[l_i-1], nums[b_i]); reverse(nums, l_i, len); } // [start, end) // [...start, start+1, ...i, i+1,...,end-1] void reverse(vector< int > & nums, int start, int end){ for ( int i = start; i < start + (end-start)/2; ++i){ int temp = nums[i]; nums[i] = nums[end + start -1 - i]; nums[end + start -1 - i] = temp; } } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class Solution { public : void nextPermutation(vector< int > &num) { if (num.empty()) return ; // in reverse order, find the first number which is in increasing trend (we call it violated number here) int i; for (i = num.size()-2; i >= 0; --i) { if (num[i] < num[i+1]) break ; } // reverse all the numbers after violated number reverse(begin(num)+i+1, end(num)); // if violated number not found, because we have reversed the whole array, then we are done! if (i == -1) return ; // else binary search find the first number larger than the violated number auto itr = upper_bound(begin(num)+i+1, end(num), num[i]); // swap them, done! swap(num[i], *itr); } }; |
原文:http://www.cnblogs.com/zhxshseu/p/b81fe57458524cf3c95743a5552cc0f7.html