π One-stop destination for all your technical interview Preparation π
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.
k
such that nums[k] < nums[k + 1]
. If no such index exists, just reverse nums
and done.
2.From back find the largest index l > k
such that nums[k] < nums[l]
. 3.Swap
nums[k]
and nums[l]
. 4.Reverse
the sub-array nums[k + 1:]
.class Solution {
public:
void nextPermutation(vector<int>& nums)
{
int n = nums.size(), k, l;
for (k = n - 2; k >= 0; k--) { // Step 1
if (nums[k] < nums[k + 1]) {
break;
}
}
if (k < 0) {
reverse(nums.begin(), nums.end());
} else {
for (l = n - 1; l > k; l--) { // Step 2
if (nums[l] > nums[k]) {
break;
}
}
swap(nums[k], nums[l]); //Step 3
reverse(nums.begin() + k + 1, nums.end()); //Step 4
}
}
};
next_permutation(a.being(),a.end())
function in c++.class Solution {
public:
void nextPermutation(vector<int>& nums){
next_permutation(nums.begin(), nums.end());
}
};