77.go 952 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func combinIter(n int, k int, last []int, res *[][]int) {
  6. solution := make([]int, len(last))
  7. copy(solution, last)
  8. if k == 0 {
  9. *res = append(*res, solution)
  10. return
  11. }
  12. var i int
  13. if len(solution) != 0 {
  14. i = solution[len(solution)-1] + 1
  15. } else {
  16. i = 1
  17. }
  18. for ; i <= n; i++ {
  19. combinIter(n, k-1, append(solution, i), res)
  20. }
  21. }
  22. func combineOld(n int, k int) (res [][]int) {
  23. combinIter(n, k, []int{}, &res)
  24. return
  25. }
  26. // a cleaner way of recursion
  27. func combine(n int, k int) (res [][]int) {
  28. // Cnn or C0n
  29. if n == k || k == 0 {
  30. row := make([]int, k)
  31. for i := range row {
  32. row[i] = i + 1
  33. }
  34. return append(res, row)
  35. }
  36. // C(k)(n) = C(k-1)(n-1) + C(k)(n-1)
  37. for _, row := range combine(n-1, k-1) {
  38. row = append(row, n)
  39. res = append(res, row)
  40. }
  41. res = append(res, combine(n-1, k)...)
  42. return
  43. }
  44. func main() {
  45. fmt.Println(combine(4, 2))
  46. fmt.Println(combine(5, 4))
  47. fmt.Println(combine(1, 1))
  48. }