31_Next Permutation
Last updated
Was this helpful?
Last updated
Was this helpful?
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 and use only constant extra memory.
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: