题意:

image.png

解题思路:

  1. 思路:DFS深度优先搜索[回溯],具体过程看图示;

图示:

image.png

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param Integer $n
  4. * @param Integer $k
  5. * @return Integer[][]
  6. */
  7. public $res = [];
  8. function combine($n, $k) {
  9. $this->dfs([], $n, $k, 1);
  10. return $this->res;
  11. }
  12. function dfs($array, $n, $k, $start) {
  13. if ($k == 0) {
  14. array_push($this->res, $array);
  15. return;
  16. }
  17. for ($i = $start; $i <= $n; $i++) {
  18. array_push($array, $i);
  19. $this->dfs($array, $n, $k - 1, $i + 1);
  20. array_pop($array);
  21. }
  22. }
  23. }

GO代码实现:

  1. var res [][]int
  2. func combine(n int, k int) [][]int {
  3. res = [][]int{}
  4. var mapT []int
  5. dfs(mapT, n, k, 1)
  6. return res
  7. }
  8. func dfs(t []int, n int, k int, start int) {
  9. if 0 == k {
  10. s := make([]int, len(t))
  11. copy(s, t)
  12. res = append(res, s)
  13. return
  14. }
  15. for i := start; i <= n-k+1; i++ {
  16. t = append(t, i)
  17. dfs(t, n, k - 1, i + 1)
  18. t = t[:len(t)-1]
  19. }
  20. }