Backtracking · Medium
A small batch contains positive workload amounts, and an experiment must select exactly k entries with an exact total. Each entry is an independent choice even when amounts repeat. The batch size permits explicit include-or-exclude search.
Count subsets of exactly k distinct indexes whose values sum to the target amount.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ nums: integer[], k: integer, target: integer }
Fields
- nums contains positive integers and each index may be selected once.
- k is the required number of selected indexes; target is the exact non-negative sum.
Output
Return value
- Return an integer count. Selection order does not matter; different index sets count separately.
- For k = 0, return one only when target is zero. If k exceeds the batch length, return zero.
Constraints
- 0 <= nums.length <= 20; 1 <= nums[i] <= 1000000.
- 0 <= k <= 25; 0 <= target <= 20000000. Counts fit a safe JSON integer.
Examples
Example 1
{
"k": 2,
"nums": [
2,
2,
3
],
"target": 5
}Returns
2Example 2
{
"k": 2,
"nums": [
1,
2,
3
],
"target": 3
}Returns
1Required complexity
O(2ⁿ) worst-case time and O(n) recursion space