31.go 952 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package main
  2. import (
  3. "fmt"
  4. )
  5. // “字典序”
  6. func nextPermutation(nums []int) {
  7. if len(nums) < 2 {
  8. return
  9. }
  10. // rfind first num descended 'ni'
  11. // 346987521 -> 34 '6' 987521
  12. i := len(nums) - 2
  13. for ; i >= 0 && nums[i] >= nums[i+1]; i-- {
  14. }
  15. if i != -1 {
  16. // find the last num 'nj' which is larger than 'ni'
  17. // swap 'nj', 'ni'
  18. // 34 '6' 987521 -> 34 '6' 98 '7' 521 -> 34 '7' 98 '6' 521
  19. j := i + 1
  20. for ; j+1 < len(nums) && nums[j+1] > nums[i]; j++ {
  21. }
  22. nums[i], nums[j] = nums[j], nums[i]
  23. }
  24. // reverse the sequence after pos 'i'
  25. // 34 '7' '986521' -> 34 '7' '125689'
  26. for l, r := i+1, len(nums)-1; l < r; l, r = l+1, r-1 {
  27. nums[l], nums[r] = nums[r], nums[l]
  28. }
  29. }
  30. func main() {
  31. a1 := []int{1, 2, 3}
  32. a2 := []int{3, 2, 1}
  33. a3 := []int{2, 3, 1}
  34. a4 := []int{1, 2, 2, 1}
  35. nextPermutation(a1)
  36. nextPermutation(a2)
  37. nextPermutation(a3)
  38. nextPermutation(a4)
  39. fmt.Println(a1)
  40. fmt.Println(a2)
  41. fmt.Println(a3)
  42. fmt.Println(a4)
  43. }