46.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func nextPermutation(nums []int) {
  6. if len(nums) < 2 {
  7. return
  8. }
  9. // rfind first num descended 'ni'
  10. // 346987521 -> 34 '6' 987521
  11. i := len(nums) - 2
  12. for ; i >= 0 && nums[i] >= nums[i+1]; i-- {
  13. }
  14. if i != -1 {
  15. // find the last num 'nj' which is larger than 'ni'
  16. // swap 'nj', 'ni'
  17. // 34 '6' 987521 -> 34 '6' 98 '7' 521 -> 34 '7' 98 '6' 521
  18. j := i + 1
  19. for ; j+1 < len(nums) && nums[j+1] > nums[i]; j++ {
  20. }
  21. nums[i], nums[j] = nums[j], nums[i]
  22. }
  23. // reverse the sequence after pos 'i'
  24. // 34 '7' '986521' -> 34 '7' '125689'
  25. for l, r := i+1, len(nums)-1; l < r; l, r = l+1, r-1 {
  26. nums[l], nums[r] = nums[r], nums[l]
  27. }
  28. }
  29. func permute(nums []int) [][]int {
  30. if len(nums) == 0 {
  31. return [][]int{}
  32. }
  33. cnt := 1
  34. for i := 2; i <= len(nums); i++ {
  35. cnt *= i
  36. }
  37. res := [][]int{nums}
  38. last := make([]int, len(nums))
  39. copy(last, nums)
  40. for i := 0; i < cnt-1; i++ {
  41. solution := make([]int, len(last))
  42. copy(solution, last)
  43. nextPermutation(solution)
  44. copy(last, solution)
  45. res = append(res, solution)
  46. }
  47. return res
  48. }
  49. func main() {
  50. a1 := []int{1, 2, 3}
  51. fmt.Println(permute(a1))
  52. }