| 13 | class Solution { |
| 14 | public: |
| 15 | void nextPermutation(vector<int>& nums) { |
| 16 | if (nums.size() <= 1) return; |
| 17 | // traverse from back to front to find the first i that |
| 18 | // nums[i] < nums[i+1] |
| 19 | int i = nums.size() - 2; |
| 20 | while (nums[i] >= nums[i+1]) { |
| 21 | if (i == 0) { |
| 22 | reverse(nums.begin(), nums.end()); |
| 23 | return; |
| 24 | } else i -- ; |
| 25 | } |
| 26 | // traverse from back to front to find the first j that |
| 27 | // nums[j] > nums[i] , i < j < nums.size() |
| 28 | int j = nums.size() - 1; |
| 29 | while (nums[j] <= nums[i]) j -- ; |
| 30 | |
| 31 | swap(nums[i], nums[j]); |
| 32 | |
| 33 | // reverse the nums[i+1..nums.size()] so that it is the smallest |
| 34 | reverse(nums.begin() + i + 1, nums.end()); |
| 35 | } |
| 36 | }; |
| 37 | |
| 38 | int main() { |
nothing calls this directly
no outgoing calls
no test coverage detected