77.go 945 B

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