[Problem]
(1)从后往前i = n-1 ~ 1,查找num[i] > num[i-1]的第一个i,说明这个地方的位置为初始位置(num[i-1] < num[i]),下一个排列需要替换num[i-1],从后往前 j = n-1 ~ i,查找第一个比num[i-1]大的数,交换num[i-1]和num[j],并将num[i:end]重新排序。
(2)如果无法找到满足上述条件的i,说明整个排列为逆序排列,那么下一个排列即为正序排列,只需要对num进行sort就行。
[Solution]
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.1,2,3
→
1,3,2
3,2,1
→
1,2,3
1,1,5
→
1,5,1
[Analysis]
(1)从后往前i = n-1 ~ 1,查找num[i] > num[i-1]的第一个i,说明这个地方的位置为初始位置(num[i-1] < num[i]),下一个排列需要替换num[i-1],从后往前 j = n-1 ~ i,查找第一个比num[i-1]大的数,交换num[i-1]和num[j],并将num[i:end]重新排序。
(2)如果无法找到满足上述条件的i,说明整个排列为逆序排列,那么下一个排列即为正序排列,只需要对num进行sort就行。
[Solution]
class Solution {说明:版权所有,转载请注明出处。 Coder007的博客
public:
/**
* swap num[i] and num[j]
*/
void swap(vector<int> &num, int i, int j){
int tmp = num[i];
num[i] = num[j];
num[j] = tmp;
}
/**
* sort num[i:end)
*/
void mySort(vector<int> &num, int i){
vector<int>::iterator it;
it = num.begin();
for(int k = 0; k < i; ++k){
it++;
}
sort(it, num.end());
}
/**
* next permutation
*/
void nextPermutation(vector<int> &num) {
// Note: The Solution object is instantiated only once and is reused by each test case.
bool done = false;
for(int i = num.size()-1; i > 0; --i){
if(num[i] > num[i-1]){
for(int j = num.size()-1; j > i-1; --j){
if(num[j] > num[i-1]){
// swap
swap(num, i-1, j);
// sort
mySort(num, i);
// break
done = true;
break;
}
}
break;
}
}
// the last permutation
if(!done){
sort(num.begin(), num.end());
}
}
};