DevPath

← All problems

Count Distinct Combinations (Each Used Once)

Medium backtracking

Description

Each candidate may be used at most once and the list may contain duplicates. Return the number of distinct combinations that sum to target.

Constraints

1 <= candidates <= 100; 1 <= target <= 500

Examples

Input: candidates = [10,1,2,7,6,1,5], target = 8

Output: 4

Hints (1)
  • Sort and skip equal candidates at the same depth.

Solutions

Sort and skip duplicates. (requires "sort") · Time exponential · Space O(n)

func combinationSum2Count(candidates []int, target int) int {
    sort.Ints(candidates)
    count := 0
    var dfs func(start, remaining int)
    dfs = func(start, remaining int) {
        if remaining == 0 {
            count++
            return
        }
        for i := start; i < len(candidates); i++ {
            if i > start && candidates[i] == candidates[i-1] {
                continue
            }
            if candidates[i] > remaining {
                break
            }
            dfs(i+1, remaining-candidates[i])
        }
    }
    dfs(0, target)
    return count
}

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

Create account