This commit is contained in:
Sainnhe Park 2022-11-21 14:45:25 +08:00
parent 8901afccf4
commit 0872014b91
2 changed files with 29 additions and 0 deletions

View File

@ -0,0 +1,13 @@
#ifndef S0031_NEXT_PERMUTATION
#define S0031_NEXT_PERMUTATION
#include <vector>
using namespace std;
class Solution {
public:
void nextPermutation(vector<int>& nums);
};
#endif

View File

@ -0,0 +1,16 @@
#include "s0031_next_permutation.hpp"
void Solution::nextPermutation(vector<int>& nums) {
int i = nums.size() - 2;
while (i >= 0 && nums[i] >= nums[i + 1]) {
i--;
}
if (i >= 0) {
int j = nums.size() - 1;
while (j >= 0 && nums[i] >= nums[j]) {
j--;
}
swap(nums[i], nums[j]);
}
reverse(nums.begin() + i + 1, nums.end());
}