MCPcopy Create free account
hub / github.com/Ainevsia/Leetcode-Rust / nextPermutation

Method nextPermutation

31. Next Permutation/Solution.cpp:15–35  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

13class Solution {
14public:
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
38int main() {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected