31_Next Permutation
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 and use only constant extra memory.
Example
Solution
Idea
find k such that nums[k-1] < nums[k] and entries after index k appear in decreasing order
find the smallest nums[l] such that l>k-1, nums[l] > nums[k-1], and nums[l-1] <= nums[k-1]
swap p[l] and p[k-1]
reverse the sequence on the right of p[k]
Time Complexity:
Space Complexity:
Last updated