next_permutation, prev_permutation
ν¨μμ 벑ν°μ iteratorλ λ°°μ΄μ μ£Όμλ₯Ό λ£μΌλ©΄ λ€μ μμ΄(next_permutation) λλ μ΄μ μμ΄(prev_permutation)μ κ²°κ³Όκ° λ²‘ν°λ λ°°μ΄μ μ μ©λλ€. λ§μ½ λ€μ λλ μ΄μ μμ΄μ΄ μλ€λ©΄ Falseλ₯Ό return νλ€.
λ¬Έμ
https://www.acmicpc.net/problem/10972
#include <iostream>
#include <algorithm>
using namespace std;
int num[10000];
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; ++i)
cin >> num[i];
if (next_permutation(num, num + n))
for (int i = 0; i < n; ++i)
cout << num[i] << " ";
else
cout << -1;
}
https://www.acmicpc.net/problem/10973
#include <iostream>
#include <algorithm>
using namespace std;
int num[10000];
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; ++i)
cin >> num[i];
if (prev_permutation(num, num + n))
for (int i = 0; i < n; ++i)
cout << num[i] << " ";
else
cout << -1;
}
https://leetcode.com/problems/next-permutation/
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
void nextPermutation(vector<int>& nums)
{
// μ°Έκ³ λ‘, μ 곡νλ μκ³ λ¦¬μ¦μ΄ μλ€.
//next_permutation(nums.begin(), nums.end());
// λ€μμλΆν° μ λ ¬μ΄ κΉ¨μ§λ μΈλ±μ€ μ°ΎκΈ°
int i = nums.size() - 2;
while (i >= 0 && nums[i] >= nums[i + 1])
--i;
if (i == -1) {
reverse(nums.begin(), nums.end());
}
else {
// μ λ ¬μ΄ κΉ¨μ§λ μΈλ±μ€ κ΅ν
int j = i + 1;
while (j < nums.size() && nums[i] < nums[j])
j++;
swap(nums[i], nums[j - 1]);
reverse(nums.begin() + i + 1, nums.end());
}
}
};