题意:

image.png

解题思路:

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

图示:

image.png

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param Integer[] $nums
  4. * @return Integer[][]
  5. */
  6. public $res = [];
  7. function subsets($nums) {
  8. return $this->subsets1($nums);
  9. /* if (!$nums) return [];
  10. $this->do([],$nums, 0);
  11. return $this->res;*/
  12. }
  13. function do($arr, $nums, $start) {
  14. array_push($this->res, $arr);
  15. for ($i = $start; $i < count($nums); $i++) {
  16. array_push($arr, $nums[$i]);
  17. $this->do($arr, $nums, $i + 1);
  18. array_pop($arr);
  19. }
  20. }
  21. //0(2^)
  22. function subsets1($nums) {
  23. if (empty($nums)) return [];
  24. $result = [];
  25. $this->helper($nums, 0, [], $result);
  26. return $result;
  27. }
  28. function helper($nums, $index, $current, &$result) {
  29. // terminator
  30. if ($index == count($nums)) {
  31. $result[] = $current;
  32. return;
  33. }
  34. // split and drill down
  35. // 不选 not pick the number in this index
  36. $this->helper($nums, $index+1, $current, $result);
  37. //选
  38. $current[] = $nums[$index];
  39. $this->helper($nums, $index+1, $current, $result);
  40. }
  41. }

GO代码实现:

  1. var res [][]int
  2. func subsets(nums []int) [][]int {
  3. res = [][]int{}
  4. var path []int
  5. subsetsBacktrack(nums, path, 0);
  6. return res;
  7. }
  8. func subsetsBacktrack(nums []int, path []int, start int){
  9. temp := make([]int, len(path))
  10. copy(temp, path)
  11. res = append(res, temp)
  12. for i := start; i < len(nums); i++ {
  13. path = append(path, nums[i])
  14. subsetsBacktrack(nums, path, i+1)
  15. path = path[:len(path)-1]
  16. }
  17. }