31.go 945 B

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