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
Well, this is more like a math problem, and I don't know how to solve it.
From the wikipedia, one classic algorithm to generate next permutation is:
The following algorithm generates the next permutation lexicographically after a given permutation. It changes the given permutation in-place.
1. Find the largest index k such that a[k] < a[k + 1]. If no such index exists, the permutation is the last permutation.
2. Find the largest index l greater than k such that a[k] < a[l].
3. Swap the value of a[k] with that of a[l].
4. Reverse the sequence from a[k + 1] up to and including the final element a[n].
For example, given the sequence [1, 2, 3, 4] which starts in a weakly increasing order, and given that the index is zero-based, the steps are as follows:
Index k = 2, because 3 is placed at an index that satisfies condition of being the largest index that is still less than a[k + 1] which is 4.
Index l = 3, because 4 is the only value in the sequence that is greater than 3 in order to satisfy the condition a[k] < a[l].
The values of a[2] and a[3] are swapped to form the new sequence [1,2,4,3].
The sequence after k-index a[2] to the final element is reversed. Because only one value lies after this index (the 3), the sequence remains unchanged in this instance. Thus the lexicographic successor of the initial state is permuted: [1,2,4,3].
Following this algorithm, the next lexicographic permutation will be [1,3,2,4], and the 24th permutation will be [4,3,2,1] at which point a[k] < a[k + 1] does not exist, indicating that this is the last permutation.
Java
public void nextPermutation(int[] num) {
int len = num.length;
int k=-1;
int l=-1;
for(int i=0;i<len-1;i++){//step1
if(num[i]<num[i+1])
k = i;
}
if(k==-1){
Arrays.sort(num);
return;
}
for(int i=0;i<len;i++){//step2
if(num[i]>num[k])
l = i;
}
int temp = num[k];//step3
num[k] = num[l];
num[l] = temp;
l = len-1;
for(int i=k+1;i<l;i++){//step4
int swap = num[i];
num[i] = num[l];
num[l--] = swap;
}
}
c++
void nextPermutation(vector<int> &num) {
int vioIndex = num.size()-1;
while(vioIndex >0){
if(num[vioIndex]>num[vioIndex-1])
break;
vioIndex--;
}
if(vioIndex>0){
vioIndex--;
int rightIndex = num.size()-1;
while(rightIndex>=0 && num[rightIndex]<=num[vioIndex]){
rightIndex--;
}
int swap = num[vioIndex];
num[vioIndex] = num[rightIndex];
num[rightIndex] = swap;
vioIndex++;
}
int end = num.size()-1;
while(end>vioIndex){
int swap = num[vioIndex];
num[vioIndex] = num[end];
num[end] = swap;
vioIndex++;
end--;
}
}