1package funk 2 3import "errors" 4 5// NextPermutation Implement next permutation, 6// which rearranges numbers into the lexicographically next greater permutation of numbers. 7func NextPermutation(nums []int) error { 8 n := len(nums) 9 if n == 0 { 10 return errors.New("nums is empty") 11 } 12 13 i := n - 2 14 15 for i >= 0 && nums[i] >= nums[i+1] { 16 i-- 17 } 18 19 if i >= 0 { 20 j := n - 1 21 for j >= 0 && nums[i] >= nums[j] { 22 j-- 23 } 24 nums[i], nums[j] = nums[j], nums[i] 25 } 26 27 ReverseInt(nums[i+1:]) 28 return nil 29} 30