题意:
解题思路:
思路:
1. 先排序,让相同的元素前后排一起;
2. 同一层级,前后相同,则跳出:前后相同指的是对应的索引值
图示:
PHP代码实现:
class Solution {
/**
* @param Integer[] $nums
* @return Integer[][]
*/
public $res = [];
function subsetsWithDup($nums) {
sort($nums);
$this->dfs([], $nums, 0);
return $this->res;
}
function dfs($array, $nums, $start) {
array_push($this->res, $array);
for ($i = $start; $i < count($nums); $i++) {
if ($i != $start && $nums[$i] == $nums[$i - 1]) {
continue;
}
array_push($array, $nums[$i]);
$this->dfs($array, $nums, $i + 1);
array_pop($array);
}
}
}
GO代码实现:
var res [][]int
func subsetsWithDup(nums []int) [][]int {
res = make([][]int, 0)
sort.Ints(nums)
dfs([]int{}, nums, 0)
return res
}
func dfs(array, nums []int, start int) {
tmp := make([]int, len(array))
copy(tmp, array)
res = append(res, tmp)
for i := start; i < len(nums); i++ {
if i > start && nums[i] == nums[i - 1] {
continue;
}
array = append(array, nums[i])
dfs(array, nums, i + 1)
array = array[:len(array) - 1]
}
}