Yu's Coding Garden : leetcode Question 61: Next permutation
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
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.
From http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html From right to left, find the fir5t digit (PartitionNumber)which violate the increase trend, in this example, 6 will be selected since 8,7,4,3,2 already in a increase trend.1,2,3
→ 1,3,2
3,2,1
→ 1,2,3
1,1,5
→ 1,5,1
From right to left, find the first digit which large than PartitionNumber, call it changeNumber Here the 7 will be selected.
Swap the PartitionNumber and ChangeNumber-
Reverse all the digit on the right of partition index
void nextPermutation(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
assert(num.size() >0);
int vioIndex = num.size() -1;
while(vioIndex >0)
{
if(num[vioIndex-1] < num[vioIndex])
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;
end--;
vioIndex++;
}
}
Also refer to http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html
Read full article from Yu's Coding Garden : leetcode Question 61: Next permutation