Given a sequence (string or array) of comparable elements, produce the lexicographically next permutation in-place. If the input is the highest permutation (sorted in descending order), transform it into the lowest permutation (sorted in ascending order) or indicate that no larger permutation exists.
This is the canonical “next permutation” operation used by std::next_permutation and appears as LeetCode 31.
Traverse from right to left to find the first position where the sequence increases (i). Swapping at that pivot with the smallest larger element to its right (j) and reversing the tail produces the next permutation with the minimal increase.
classSolution {
public:void nextPermutation(std::vector<int>& nums) {
int n = nums.size();
int i = n -1;
while (i >0&& nums[i -1] >= nums[i]) --i;
if (i <=0) { std::reverse(nums.begin(), nums.end()); return; }
int j = n -1;
while (nums[j] <= nums[i -1]) --j;
std::swap(nums[i -1], nums[j]);
std::reverse(nums.begin() + i, nums.end());
}
};
classSolution {
publicvoidnextPermutation(int[] nums) {
int n = nums.length;
int i = n - 1;
while (i > 0 && nums[i - 1]>= nums[i]) i--;
if (i <= 0) { reverse(nums, 0, n - 1); return; }
int j = n - 1;
while (nums[j]<= nums[i - 1]) j--;
int tmp = nums[i - 1]; nums[i - 1]= nums[j]; nums[j]= tmp;
reverse(nums, i, n - 1);
}
privatevoidreverse(int[] a, int l, int r) {
while (l < r) { int t = a[l]; a[l++]= a[r]; a[r--]= t; }
}
}