90. 子集 II

链接 (opens new window)

20240215133529_image.png

class Solution {

    public $result;

    /**
     * @param  Integer[]  $nums
     * @return Integer[][]
     */
    function subsetsWithDup($nums) {
        sort($nums);
        $this->dfs($nums, 0, []);
        return $this->result;
    }

    function dfs($nums, $start, $path) {
        $this->result[] = $path;
        for ($i = $start, $iMax = count($nums); $i < $iMax; $i++) {
            //同一层级相同元素非第一个分支剪枝 注意需要排序后才方便去重
            if($i > $start && $nums[$i] == $nums[$i - 1]) continue;
            $path[] = $nums[$i];
            $this->dfs($nums, $i + 1, $path);
            array_pop($path);
        }
    }
}
copy success
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25