DevPath

← All problems

Count Distinct Subsets

Medium backtracking

Description

Return the number of distinct subsets of an array that may contain duplicates.

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
}

Create a free account to submit solutions, track progress and save problems.

Create account