Count Distinct Combinations (Each Used Once)
Medium backtracking
Description
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
}
Sort and skip duplicates. · Time exponential · Space O(n)
function combinationSum2Count(candidates, target) {
candidates = [...candidates].sort((a, b) => a - b);
let count = 0;
const dfs = (start, remaining) => {
if (remaining === 0) { count++; return; }
for (let i = start; i < candidates.length; 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;
}
Sort and skip duplicates. · Time exponential · Space O(n)
function combinationSum2Count($candidates, $target) {
sort($candidates);
$count = 0;
$dfs = function ($start, $remaining) use (&$dfs, &$count, $candidates) {
if ($remaining === 0) { $count++; return; }
for ($i = $start; $i < count($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;
}
Sort and skip duplicates. · Time exponential · Space O(n)
def combinationSum2Count(candidates, target):
a = sorted(candidates)
count = 0
def dfs(start, remaining):
nonlocal count
if remaining == 0:
count += 1
return
for i in range(start, len(a)):
if i > start and a[i] == a[i - 1]:
continue
if a[i] > remaining:
break
dfs(i + 1, remaining - a[i])
dfs(0, target)
return count
Sort and skip duplicates. · Time exponential · Space O(n)
function combinationSum2Count(candidates: number[], target: number): number {
const a = [...candidates].sort((x, y) => x - y);
let count = 0;
const dfs = (start: number, remaining: number): void => {
if (remaining === 0) { count++; return; }
for (let i = start; i < a.length; i++) {
if (i > start && a[i] === a[i - 1]) continue;
if (a[i] > remaining) break;
dfs(i + 1, remaining - a[i]);
}
};
dfs(0, target);
return count;
}
Create a free account to submit solutions, track progress and save problems.
Create account