-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnext-permutation.cpp
30 lines (30 loc) · 1.08 KB
/
next-permutation.cpp
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
class Solution {
public:
void nextPermutation(vector<int> &v) {
int to_change = -1, be_changed = -1;
for(int idx = v.size() - 1; idx >= 0; idx--) {
for(int jdx = idx - 1; jdx >= 0; jdx--) {
if(v[idx] > v[jdx]) { // can be changed
if(to_change == -1) {
to_change = jdx;
be_changed = idx;
} else {
if(to_change < jdx) { // choose the least significant digit to change
to_change = jdx;
be_changed = idx;
} else if(to_change == jdx && v[idx] < v[be_changed]) { // the smaller the better
be_changed = idx;
}
}
}
}
}
if(to_change != -1) {
swap(v[to_change], v[be_changed]);
sort(v.begin() + to_change + 1, v.end()); // sort the remaining
} else {
sort(v.begin(), v.end());
}
return;
}
};