Count Distinct Subsets
Medium backtracking
Description
Constraints
0 <= n <= 20
Examples
Input: nums = [1,2,2]
Output: 6
Hints (1)
- Sort and skip a value at the same depth once it has been used.
Solutions
Sort and skip duplicates per depth. (requires "sort") · Time exponential · Space O(n)
func subsetsWithDupCount(nums []int) int {
sort.Ints(nums)
count := 0
var dfs func(start int)
dfs = func(start int) {
count++
for i := start; i < len(nums); i++ {
if i > start && nums[i] == nums[i-1] {
continue
}
dfs(i + 1)
}
}
dfs(0)
return count
}
Sort and skip duplicates per depth. · Time exponential · Space O(n)
function subsetsWithDupCount(nums) {
const a = [...nums].sort((x, y) => x - y);
let count = 0;
const dfs = (start) => {
count++;
for (let i = start; i < a.length; i++) {
if (i > start && a[i] === a[i - 1]) continue;
dfs(i + 1);
}
};
dfs(0);
return count;
}
Sort and skip duplicates per depth. · Time exponential · Space O(n)
function subsetsWithDupCount($nums) {
sort($nums);
$count = 0;
$dfs = function ($start) use (&$dfs, &$count, $nums) {
$count++;
for ($i = $start; $i < count($nums); $i++) {
if ($i > $start && $nums[$i] === $nums[$i - 1]) { continue; }
$dfs($i + 1);
}
};
$dfs(0);
return $count;
}
Sort and skip duplicates per depth. · Time exponential · Space O(n)
def subsetsWithDupCount(nums):
a = sorted(nums)
count = 0
def dfs(start):
nonlocal count
count += 1
for i in range(start, len(a)):
if i > start and a[i] == a[i - 1]:
continue
dfs(i + 1)
dfs(0)
return count
Sort and skip duplicates per depth. · Time exponential · Space O(n)
function subsetsWithDupCount(nums: number[]): number {
const a = [...nums].sort((x, y) => x - y);
let count = 0;
const dfs = (start: number): void => {
count++;
for (let i = start; i < a.length; i++) {
if (i > start && a[i] === a[i - 1]) continue;
dfs(i + 1);
}
};
dfs(0);
return count;
}
Create a free account to submit solutions, track progress and save problems.
Create account