[LeetCode] Next Permutation

31. Next Permutation

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order).

The replacement must be in place and use only constant extra memory.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Solution {
private:
bool isFinish = false;
bool isDesc(vector<int>& nums, vector<int>& cnt, int& MAX) {
bool flag = true;
cnt[nums[0]]++;
MAX = max(MAX, nums[0]);
for(int i = 1; i < nums.size(); ++i){
if(nums[i] > nums[i - 1])
flag = false;
MAX = max(MAX, nums[i]);
cnt[nums[i]]++;
}

return flag;
}

void recursive(vector<int>& nums, vector<int>& tmp, vector<int>& cnt, const int max, int pos, bool flag) {
if(pos == nums.size()) {
if(flag){
nums = tmp;
isFinish = true;
}
return ;
}

for(int i = flag == 1 ? 0 : nums[pos]; i <= max; ++i) {
if(!cnt[i]) continue;
cnt[i]--;
tmp[pos] = i;
recursive(nums, tmp, cnt, max, pos + 1, flag ? flag : nums[pos] < i);
if(isFinish)
return ;
cnt[i]++;
}
return ;
}
public:
void nextPermutation(vector<int>& nums) {
if(nums.size() == 1)
return;
vector<int> cnt(101,0);
int max = 0;
if(isDesc(nums, cnt, max)) {
sort(begin(nums), end(nums));
return;
}
vector<int> res(nums.size());
recursive(nums, res, cnt, max, 0, false);
return ;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/01/PS/LeetCode/next-permutation/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.