layout: posttitle: PHP 回溯算法求解子集问题
subtitle: PHP 回溯算法求解子集问题
date: 2020-09-21
author: he xiaodong
header-img: img/default-post-bg.jpg
catalog: true
tags:
- Go
- PHP
- LeetCode 78
- 回溯算法
- 子集

子集

给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。

示例:

  1. 输入: nums = [1,2,3]
  2. 输出:
  3. [
  4. [3],
  5. [1],
  6. [2],
  7. [1,2,3],
  8. [1,3],
  9. [2,3],
  10. [1,2],
  11. []
  12. ]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subsets

解题思路 1

直接参考 回溯算法团灭排列/组合/子集问题

代码
  1. class Solution {
  2. public $result = [];
  3. /**
  4. * @param Integer[] $nums
  5. * @return Integer[][]
  6. */
  7. function subsets($nums) {
  8. $this->dfs(0, $nums, []);
  9. return $this->result;
  10. }
  11. // 递归部分
  12. function dfs($start, $nums, $array){
  13. $this->result[] = $array;
  14. for ($i = $start; $i < count($nums); $i++) {
  15. $array[] = $nums[$i];
  16. $this->dfs($i + 1, $nums, $array);
  17. array_pop($array);
  18. }
  19. }
  20. }

解题思路 2 迭代法
  1. 初始化结果为 二维空数组
  2. 遍历给定数组中的每一个元素,在每一次遍历中,处理结果集。结果集中的每个元素添加遍历到的数字,结果集的长度不断增加。
  1. class Solution {
  2. /**
  3. * @param Integer[] $nums
  4. * @return Integer[][]
  5. */
  6. function subsets($nums) {
  7. $result = [];
  8. $result[] = [];
  9. $numsCount = count($nums);
  10. for ($i = 0; $i < $numsCount; $i++) {
  11. $resultCount = count($result);
  12. for ($j = 0; $j < $resultCount; $j++) {
  13. $tmp = $result[$j];
  14. $tmp[] = $nums[$i];
  15. $result[] = $tmp;
  16. }
  17. }
  18. return $result;
  19. }
  20. }

参考链接

  1. 回溯算法团灭排列/组合/子集问题

最后恰饭 阿里云全系列产品/短信包特惠购买 中小企业上云最佳选择 阿里云内部优惠券