void nextPermutation(vector<int>& nums) { // time: O(n); space: O(1)
int n = nums.size();
for (int i = n - 2; i >= 0; --i) {
if (nums[i] < nums[i + 1]) {
int j;
for (j = n - 1; j > i; --j) {
if (nums[j] > nums[i]) break;
}
swap(nums[i], nums[j]);
reverse(nums.begin() + i + 1, nums.end());
return;
}
}
reverse(nums.begin(), nums.end());
}
void nextPermutation(vector<int>& nums) { // time: O(n); space: O(1)
int n = nums.size(), i = n - 2, j = n - 1;
// Search from the end to find the first element which is not ascending
while (i >= 0 && nums[i] >= nums[i + 1]) --i;
if (i >= 0) {
// Search from the end to find the first element which is larger than nums[i]
while (nums[i] >= nums[j]) --j;
swap(nums[i], nums[j]);
}
reverse(nums.begin() + i + 1, nums.end());
}