13.3 Subset sum problem¶
13.3.1 Distinct elements¶
Question
Given an array of positive integers nums and a positive target integer target, find all combinations whose elements sum to target. The array has no duplicate elements, and each element may be chosen multiple times. Return the combinations as a list containing no duplicates.
For example, with input \(\{3, 4, 5\}\) and target \(9\), the solutions are \(\{3, 3, 3\}, \{4, 5\}\). Keep two points in mind.
- Each input element may be chosen an unlimited number of times.
- Element order does not matter: \(\{4, 5\}\) and \(\{5, 4\}\) represent the same subset.
1. Starting from the permutations solution¶
As with permutations, we can view generating a subset as a sequence of choices. Update the sum as we make choices, and record the subset when the sum equals target.
Unlike permutations, each element may be chosen an unlimited number of times, so we do not need a Boolean selected list. A small modification to the permutations code gives an initial solution:
def backtrack(
state: list[int],
target: int,
total: int,
choices: list[int],
res: list[list[int]],
):
"""Backtracking: subset sum I"""
# Record a solution when the subset sum equals target
if total == target:
res.append(list(state))
return
# Iterate over all choices
for i in range(len(choices)):
# Prune: skip this choice if the subset sum would exceed target
if total + choices[i] > target:
continue
# Try: make a choice and update the sum total
state.append(choices[i])
# Proceed to the next choice
backtrack(state, target, total + choices[i], choices, res)
# Backtrack: undo the choice and restore the previous state
state.pop()
def subset_sum_i_naive(nums: list[int], target: int) -> list[list[int]]:
"""Solve subset sum I (with duplicate subsets)"""
state = [] # State (subset)
total = 0 # Subset sum
res = [] # Result list (list of subsets)
backtrack(state, target, total, nums, res)
return res
/* Backtracking: subset sum I */
void backtrack(vector<int> &state, int target, int total, vector<int> &choices, vector<vector<int>> &res) {
// Record a solution when the subset sum equals target
if (total == target) {
res.push_back(state);
return;
}
// Iterate over all choices
for (size_t i = 0; i < choices.size(); i++) {
// Prune: skip this choice if the subset sum would exceed target
if (total + choices[i] > target) {
continue;
}
// Try: make a choice and update the sum total
state.push_back(choices[i]);
// Proceed to the next choice
backtrack(state, target, total + choices[i], choices, res);
// Backtrack: undo the choice and restore the previous state
state.pop_back();
}
}
/* Solve subset sum I (with duplicate subsets) */
vector<vector<int>> subsetSumINaive(vector<int> &nums, int target) {
vector<int> state; // State (subset)
int total = 0; // Subset sum
vector<vector<int>> res; // Result list (list of subsets)
backtrack(state, target, total, nums, res);
return res;
}
/* Backtracking: subset sum I */
void backtrack(List<Integer> state, int target, int total, int[] choices, List<List<Integer>> res) {
// Record a solution when the subset sum equals target
if (total == target) {
res.add(new ArrayList<>(state));
return;
}
// Iterate over all choices
for (int i = 0; i < choices.length; i++) {
// Prune: skip this choice if the subset sum would exceed target
if (total + choices[i] > target) {
continue;
}
// Try: make a choice and update the sum total
state.add(choices[i]);
// Proceed to the next choice
backtrack(state, target, total + choices[i], choices, res);
// Backtrack: undo the choice and restore the previous state
state.remove(state.size() - 1);
}
}
/* Solve subset sum I (with duplicate subsets) */
List<List<Integer>> subsetSumINaive(int[] nums, int target) {
List<Integer> state = new ArrayList<>(); // State (subset)
int total = 0; // Subset sum
List<List<Integer>> res = new ArrayList<>(); // Result list (list of subsets)
backtrack(state, target, total, nums, res);
return res;
}
/* Backtracking: subset sum I */
void Backtrack(List<int> state, int target, int total, int[] choices, List<List<int>> res) {
// Record a solution when the subset sum equals target
if (total == target) {
res.Add(new List<int>(state));
return;
}
// Iterate over all choices
for (int i = 0; i < choices.Length; i++) {
// Prune: skip this choice if the subset sum would exceed target
if (total + choices[i] > target) {
continue;
}
// Try: make a choice and update the sum total
state.Add(choices[i]);
// Proceed to the next choice
Backtrack(state, target, total + choices[i], choices, res);
// Backtrack: undo the choice and restore the previous state
state.RemoveAt(state.Count - 1);
}
}
/* Solve subset sum I (with duplicate subsets) */
List<List<int>> SubsetSumINaive(int[] nums, int target) {
List<int> state = []; // State (subset)
int total = 0; // Subset sum
List<List<int>> res = []; // Result list (list of subsets)
Backtrack(state, target, total, nums, res);
return res;
}
/* Backtracking: subset sum I */
func backtrackSubsetSumINaive(total, target int, state, choices *[]int, res *[][]int) {
// Record a solution when the subset sum equals target
if target == total {
newState := append([]int{}, *state...)
*res = append(*res, newState)
return
}
// Iterate over all choices
for i := 0; i < len(*choices); i++ {
// Prune: skip this choice if the subset sum would exceed target
if total+(*choices)[i] > target {
continue
}
// Try: make a choice and update the sum total
*state = append(*state, (*choices)[i])
// Proceed to the next choice
backtrackSubsetSumINaive(total+(*choices)[i], target, state, choices, res)
// Backtrack: undo the choice and restore the previous state
*state = (*state)[:len(*state)-1]
}
}
/* Solve subset sum I (with duplicate subsets) */
func subsetSumINaive(nums []int, target int) [][]int {
state := make([]int, 0) // State (subset)
total := 0 // Subset sum
res := make([][]int, 0) // Result list (list of subsets)
backtrackSubsetSumINaive(total, target, &state, &nums, &res)
return res
}
/* Backtracking: subset sum I */
func backtrack(state: inout [Int], target: Int, total: Int, choices: [Int], res: inout [[Int]]) {
// Record a solution when the subset sum equals target
if total == target {
res.append(state)
return
}
// Iterate over all choices
for i in choices.indices {
// Prune: skip this choice if the subset sum would exceed target
if total + choices[i] > target {
continue
}
// Try: make a choice and update the sum total
state.append(choices[i])
// Proceed to the next choice
backtrack(state: &state, target: target, total: total + choices[i], choices: choices, res: &res)
// Backtrack: undo the choice and restore the previous state
state.removeLast()
}
}
/* Solve subset sum I (with duplicate subsets) */
func subsetSumINaive(nums: [Int], target: Int) -> [[Int]] {
var state: [Int] = [] // State (subset)
let total = 0 // Subset sum
var res: [[Int]] = [] // Result list (list of subsets)
backtrack(state: &state, target: target, total: total, choices: nums, res: &res)
return res
}
/* Backtracking: subset sum I */
function backtrack(state, target, total, choices, res) {
// Record a solution when the subset sum equals target
if (total === target) {
res.push([...state]);
return;
}
// Iterate over all choices
for (let i = 0; i < choices.length; i++) {
// Prune: skip this choice if the subset sum would exceed target
if (total + choices[i] > target) {
continue;
}
// Try: make a choice and update the sum total
state.push(choices[i]);
// Proceed to the next choice
backtrack(state, target, total + choices[i], choices, res);
// Backtrack: undo the choice and restore the previous state
state.pop();
}
}
/* Solve subset sum I (with duplicate subsets) */
function subsetSumINaive(nums, target) {
const state = []; // State (subset)
const total = 0; // Subset sum
const res = []; // Result list (list of subsets)
backtrack(state, target, total, nums, res);
return res;
}
/* Backtracking: subset sum I */
function backtrack(
state: number[],
target: number,
total: number,
choices: number[],
res: number[][]
): void {
// Record a solution when the subset sum equals target
if (total === target) {
res.push([...state]);
return;
}
// Iterate over all choices
for (let i = 0; i < choices.length; i++) {
// Prune: skip this choice if the subset sum would exceed target
if (total + choices[i] > target) {
continue;
}
// Try: make a choice and update the sum total
state.push(choices[i]);
// Proceed to the next choice
backtrack(state, target, total + choices[i], choices, res);
// Backtrack: undo the choice and restore the previous state
state.pop();
}
}
/* Solve subset sum I (with duplicate subsets) */
function subsetSumINaive(nums: number[], target: number): number[][] {
const state = []; // State (subset)
const total = 0; // Subset sum
const res = []; // Result list (list of subsets)
backtrack(state, target, total, nums, res);
return res;
}
/* Backtracking: subset sum I */
void backtrack(
List<int> state,
int target,
int total,
List<int> choices,
List<List<int>> res,
) {
// Record a solution when the subset sum equals target
if (total == target) {
res.add(List.from(state));
return;
}
// Iterate over all choices
for (int i = 0; i < choices.length; i++) {
// Prune: skip this choice if the subset sum would exceed target
if (total + choices[i] > target) {
continue;
}
// Try: make a choice and update the sum total
state.add(choices[i]);
// Proceed to the next choice
backtrack(state, target, total + choices[i], choices, res);
// Backtrack: undo the choice and restore the previous state
state.removeLast();
}
}
/* Solve subset sum I (with duplicate subsets) */
List<List<int>> subsetSumINaive(List<int> nums, int target) {
List<int> state = []; // State (subset)
int total = 0; // Sum of the elements
List<List<int>> res = []; // Result list (list of subsets)
backtrack(state, target, total, nums, res);
return res;
}
/* Backtracking: subset sum I */
fn backtrack(
state: &mut Vec<i32>,
target: i32,
total: i32,
choices: &[i32],
res: &mut Vec<Vec<i32>>,
) {
// Record a solution when the subset sum equals target
if total == target {
res.push(state.clone());
return;
}
// Iterate over all choices
for i in 0..choices.len() {
// Prune: skip this choice if the subset sum would exceed target
if total + choices[i] > target {
continue;
}
// Try: make a choice and update the sum total
state.push(choices[i]);
// Proceed to the next choice
backtrack(state, target, total + choices[i], choices, res);
// Backtrack: undo the choice and restore the previous state
state.pop();
}
}
/* Solve subset sum I (with duplicate subsets) */
fn subset_sum_i_naive(nums: &[i32], target: i32) -> Vec<Vec<i32>> {
let mut state = Vec::new(); // State (subset)
let total = 0; // Subset sum
let mut res = Vec::new(); // Result list (list of subsets)
backtrack(&mut state, target, total, nums, &mut res);
res
}
/* Backtracking: subset sum I */
void backtrack(int target, int total, int *choices, int choicesSize) {
// Record a solution when the subset sum equals target
if (total == target) {
for (int i = 0; i < stateSize; i++) {
res[resSize][i] = state[i];
}
resColSizes[resSize++] = stateSize;
return;
}
// Iterate over all choices
for (int i = 0; i < choicesSize; i++) {
// Prune: skip this choice if the subset sum would exceed target
if (total + choices[i] > target) {
continue;
}
// Try: make a choice and update the sum total
state[stateSize++] = choices[i];
// Proceed to the next choice
backtrack(target, total + choices[i], choices, choicesSize);
// Backtrack: undo the choice and restore the previous state
stateSize--;
}
}
/* Solve subset sum I (with duplicate subsets) */
void subsetSumINaive(int *nums, int numsSize, int target) {
resSize = 0; // Initialize the solution count to 0
backtrack(target, 0, nums, numsSize);
}
/* Backtracking: subset sum I */
fun backtrack(
state: MutableList<Int>,
target: Int,
total: Int,
choices: IntArray,
res: MutableList<MutableList<Int>?>
) {
// Record a solution when the subset sum equals target
if (total == target) {
res.add(state.toMutableList())
return
}
// Iterate over all choices
for (i in choices.indices) {
// Prune: skip this choice if the subset sum would exceed target
if (total + choices[i] > target) {
continue
}
// Try: make a choice and update the sum total
state.add(choices[i])
// Proceed to the next choice
backtrack(state, target, total + choices[i], choices, res)
// Backtrack: undo the choice and restore the previous state
state.removeAt(state.size - 1)
}
}
/* Solve subset sum I (with duplicate subsets) */
fun subsetSumINaive(nums: IntArray, target: Int): MutableList<MutableList<Int>?> {
val state = mutableListOf<Int>() // State (subset)
val total = 0 // Subset sum
val res = mutableListOf<MutableList<Int>?>() // Result list (list of subsets)
backtrack(state, target, total, nums, res)
return res
}
### Backtracking: subset sum I ###
def backtrack(state, target, total, choices, res)
# Record a solution when the subset sum equals target
if total == target
res << state.dup
return
end
# Iterate over all choices
for i in 0...choices.length
# Prune: skip this choice if the subset sum would exceed target
next if total + choices[i] > target
# Try: make a choice and update the sum total
state << choices[i]
# Proceed to the next choice
backtrack(state, target, total + choices[i], choices, res)
# Backtrack: undo the choice and restore the previous state
state.pop
end
end
### Solve subset sum I (with duplicate subsets)###
def subset_sum_i_naive(nums, target)
state = [] # State (subset)
total = 0 # Subset sum
res = [] # Result list (list of subsets)
backtrack(state, target, total, nums, res)
res
end
Visualize execution
For input array \([3, 4, 5]\) and target \(9\), this code returns \([3, 3, 3], [4, 5], [5, 4]\). It finds all subsets summing to \(9\), but includes the duplicate subsets \([4, 5]\) and \([5, 4]\).
The search distinguishes the order of choices, whereas subsets do not. As shown in Figure 13-10, choosing \(4\) then \(5\) and choosing \(5\) then \(4\) follow different branches but produce the same subset.
Figure 13-10 Subset search and pruning when the sum exceeds the target
Description of Figure 13-10: Pruning only sums exceeding the target still generates duplicate combinations
Starting from cumulative sum 0 and adding 3, 4, and 5 prunes branches exceeding 9, yet still outputs both duplicate combinations [4, 5] and [5, 4].
The input consists of the positive integer array choices = [3, 4, 5] and target sum target = 9; each element may be chosen repeatedly, and resulting subsets (combinations) ignore element order.
Each circular node shows the cumulative sum of the current prefix (0 at the root). Every round tries adding all candidates 3, 4, and 5: if the new sum exceeds 9 (pruned via a dashed > 9 branch in the figure without forming a new circular node), skip it; if it equals 9, enter the leaf node to record the result and then return to the previous level to continue trying.
The search tree has 13 solid circular state nodes. The table below lists each prefix's cumulative sum and next-round choices level by level; reaching a leaf node with sum 9 records one result, and "enter" in the parent row refers only to entering that child call. Arrows in the table denote entering the corresponding child node, with the cumulative sum written to the right of the arrow.
| Current prefix | Cumulative sum | Next-round choices or termination reason |
|---|---|---|
| [] | 0 | +3→3; +4→4; +5→5 |
| [3] | 3 | +3→6; +4→7; +5→8 |
| [4] | 4 | +3→7; +4→8; +5→9, enter [4, 5] (hits 9) |
| [5] | 5 | +3→8; +4→9, enter [5, 4] (hits 9); +5 exceeds target |
| [3, 3] | 6 | +3→9, enter [3, 3, 3] (hits 9); +4 and +5 exceed target |
| [3, 4] | 7 | +3, +4, and +5 all exceed target |
| [3, 5] | 8 | +3, +4, and +5 all exceed target |
| [4, 3] | 7 | +3, +4, and +5 all exceed target |
| [4, 4] | 8 | +3, +4, and +5 all exceed target |
| [4, 5] | 9 | Record result and return |
| [5, 3] | 8 | +3, +4, and +5 all exceed target |
| [5, 4] | 9 | Record result and return |
| [3, 3, 3] | 9 | Record result and return |
Although out-of-range pruning stops branches whose sum exceeds 9 promptly, the search still outputs three results—[3, 3, 3], [4, 5], and [5, 4]—where [4, 5] and [5, 4] are duplicate combinations containing the same elements in different orders.
One straightforward way to remove duplicate subsets is to deduplicate the result list. However, this is inefficient for two reasons.
- With many array elements, especially when
targetis large, the search generates many duplicate subsets. - Comparing subsets (arrays) is expensive: we must sort them first, then compare their elements one by one.
2. Pruning duplicate subsets¶
Instead, we can eliminate duplicates by pruning during the search. As shown in Figure 13-11, duplicates arise when array elements are chosen in different orders, as in the following example.
- Choosing \(3\) and then \(4\) in the first two rounds generates all subsets beginning with these choices, denoted by \([3, 4, \dots]\).
- Later, after choosing \(4\) first, we should skip \(3\) in the second round, because subsets \([4, 3, \dots]\) duplicate those generated in step
1..
At each level of the search, choices are tried from left to right, so branches farther to the right have more choices pruned.
- Choosing \(3\) and then \(5\) generates subsets \([3, 5, \dots]\).
- Choosing \(4\) and then \(5\) generates subsets \([4, 5, \dots]\).
- If \(5\) is chosen first, skip both \(3\) and \(4\) in the second round, because \([5, 3, \dots]\) and \([5, 4, \dots]\) duplicate the subsets described in steps
1.and2..
Figure 13-11 Duplicate subsets caused by different choice orders
Description of Figure 13-11: Avoiding duplicate combinations with nondecreasing choice indices
Restrict the next round to choose only from the current index i onward (start = i in the code below), pruning reverse-order duplicate branches that look back to earlier indices.
The candidate array is choices = [3, 4, 5] (indices 0, 1, 2), where elements may be chosen repeatedly and subsets ignore element order. This figure expands only the first two rounds of choices to compare selection order against duplicate subsets, without expanding a third round or checking the target sum.
Combinations ignore element order: picking a larger index first and then going back to a smaller index necessarily duplicates the path that picks the smaller index first and then the larger index. Thus, after choosing 4 we never go back to 3, and after choosing 5 we never go back to 3 or 4.
Because this problem allows choosing the same element repeatedly (such as [3, 3, …], [4, 4, …], and [5, 5, …]), selecting index i in the current round must set the next round's starting index to start = i rather than i + 1 so the branch that chooses the current element again is preserved. Trailing ellipses in the figure indicate unexpanded continuations; this figure compares only selection order without checking whether the target sum is reached or exceeded.
The three pruned branches are marked with grayed-out boxes, dashed lines, and scissors, and gray arcs along the bottom pair them with the kept prefixes in reverse order. The table below lists all nine two-element prefixes and the three duplicate pairs.
| Two-element prefix | Disposition | Reverse-order paired prefix | Reason |
|---|---|---|---|
| [3,3,…] | Kept | No reverse-order counterpart | Indices are nondecreasing |
| [3,4,…] | Kept | [4,3,…] | Indices are nondecreasing |
| [3,5,…] | Kept | [5,3,…] | Indices are nondecreasing |
| [4,3,…] | Skip earlier index | [3,4,…] | Produces a duplicate combination with the kept prefix |
| [4,4,…] | Kept | No reverse-order counterpart | Indices are nondecreasing |
| [4,5,…] | Kept | [5,4,…] | Indices are nondecreasing |
| [5,3,…] | Skip earlier index | [3,5,…] | Produces a duplicate combination with the kept prefix |
| [5,4,…] | Skip earlier index | [4,5,…] | Produces a duplicate combination with the kept prefix |
| [5,5,…] | Kept | No reverse-order counterpart | Indices are nondecreasing |
Among the nine prefixes across the first two rounds, the six prefixes with nondecreasing indices are kept, while the three branches that go back to an earlier index are pruned.
In general, for input \([x_1, x_2, \dots, x_n]\), a sequence of choices \([x_{i_1}, x_{i_2}, \dots, x_{i_m}]\) must satisfy \(i_1 \leq i_2 \leq \dots \leq i_m\). Any sequence violating this condition creates a duplicate and should be pruned.
3. Code implementation¶
To implement this pruning, introduce start to specify where iteration begins. After choosing \(x_{i}\), begin the next round at index \(i\). This enforces \(i_1 \leq i_2 \leq \dots \leq i_m\) and ensures that each subset is unique.
We also make two further improvements.
- Sort
numsbefore starting the search. While iterating over choices, stop the loop as soon as the subset sum exceedstarget, because all later elements are larger and would also exceed it. - Remove the sum variable
totaland track the sum by subtracting fromtarget. Record a solution whentargetreaches \(0\).
def backtrack(
state: list[int], target: int, choices: list[int], start: int, res: list[list[int]]
):
"""Backtracking: subset sum I"""
# Record a solution when the remaining target is zero
if target == 0:
res.append(list(state))
return
# Iterate over all choices
# Pruning 2: iterate from start to avoid generating duplicate subsets
for i in range(start, len(choices)):
# Pruning 1: exit the loop if this choice exceeds the remaining target
# The array is sorted, so later elements are at least as large and also exceed the remaining target
if target - choices[i] < 0:
break
# Try: make a choice and update target and start
state.append(choices[i])
# Proceed to the next choice
backtrack(state, target - choices[i], choices, i, res)
# Backtrack: undo the choice and restore the previous state
state.pop()
def subset_sum_i(nums: list[int], target: int) -> list[list[int]]:
"""Solve subset sum I"""
state = [] # State (subset)
nums.sort() # Sort nums
start = 0 # Starting index for iteration
res = [] # Result list (list of subsets)
backtrack(state, target, nums, start, res)
return res
/* Backtracking: subset sum I */
void backtrack(vector<int> &state, int target, vector<int> &choices, int start, vector<vector<int>> &res) {
// Record a solution when the remaining target reaches 0
if (target == 0) {
res.push_back(state);
return;
}
// Iterate over all choices
// Pruning 2: iterate from start to avoid generating duplicate subsets
for (int i = start; i < choices.size(); i++) {
// Pruning 1: exit the loop if this choice exceeds the remaining target
// The array is sorted, so later elements are at least as large and also exceed the remaining target
if (target - choices[i] < 0) {
break;
}
// Try: make a choice and update target and start
state.push_back(choices[i]);
// Proceed to the next choice
backtrack(state, target - choices[i], choices, i, res);
// Backtrack: undo the choice and restore the previous state
state.pop_back();
}
}
/* Solve subset sum I */
vector<vector<int>> subsetSumI(vector<int> &nums, int target) {
vector<int> state; // State (subset)
sort(nums.begin(), nums.end()); // Sort nums
int start = 0; // Starting index for iteration
vector<vector<int>> res; // Result list (list of subsets)
backtrack(state, target, nums, start, res);
return res;
}
/* Backtracking: subset sum I */
void backtrack(List<Integer> state, int target, int[] choices, int start, List<List<Integer>> res) {
// Record a solution when the remaining target is zero, so the subset sums to the original target
if (target == 0) {
res.add(new ArrayList<>(state));
return;
}
// Iterate over all choices
// Pruning 2: iterate from start to avoid generating duplicate subsets
for (int i = start; i < choices.length; i++) {
// Pruning 1: exit the loop if the next element exceeds the remaining target
// The array is sorted, so later elements are at least as large and also exceed the remaining target
if (target - choices[i] < 0) {
break;
}
// Try: make a choice and update target and start
state.add(choices[i]);
// Proceed to the next choice
backtrack(state, target - choices[i], choices, i, res);
// Backtrack: undo the choice and restore the previous state
state.remove(state.size() - 1);
}
}
/* Solve subset sum I */
List<List<Integer>> subsetSumI(int[] nums, int target) {
List<Integer> state = new ArrayList<>(); // State (subset)
Arrays.sort(nums); // Sort nums
int start = 0; // Starting index for iteration
List<List<Integer>> res = new ArrayList<>(); // Result list (list of subsets)
backtrack(state, target, nums, start, res);
return res;
}
/* Backtracking: subset sum I */
void Backtrack(List<int> state, int target, int[] choices, int start, List<List<int>> res) {
// Record a solution when the subset reaches the original target (remaining target is 0)
if (target == 0) {
res.Add(new List<int>(state));
return;
}
// Iterate over all choices
// Pruning 2: iterate from start to avoid generating duplicate subsets
for (int i = start; i < choices.Length; i++) {
// Pruning 1: exit the loop if this choice would exceed the remaining target
// The array is sorted, so later elements are at least as large and would also exceed the remaining target
if (target - choices[i] < 0) {
break;
}
// Try: make a choice and update target and start
state.Add(choices[i]);
// Proceed to the next choice
Backtrack(state, target - choices[i], choices, i, res);
// Backtrack: undo the choice and restore the previous state
state.RemoveAt(state.Count - 1);
}
}
/* Solve subset sum I */
List<List<int>> SubsetSumI(int[] nums, int target) {
List<int> state = []; // State (subset)
Array.Sort(nums); // Sort nums
int start = 0; // Starting index for iteration
List<List<int>> res = []; // Result list (list of subsets)
Backtrack(state, target, nums, start, res);
return res;
}
/* Backtracking: subset sum I */
func backtrackSubsetSumI(start, target int, state, choices *[]int, res *[][]int) {
// Record a solution when the subset reaches the original target sum (remaining target is zero)
if target == 0 {
newState := append([]int{}, *state...)
*res = append(*res, newState)
return
}
// Iterate over all choices
// Pruning 2: iterate from start to avoid generating duplicate subsets
for i := start; i < len(*choices); i++ {
// Pruning 1: exit the loop if this choice exceeds the remaining target
// The array is sorted, so later elements are at least as large and also exceed the remaining target
if target-(*choices)[i] < 0 {
break
}
// Try: make a choice and update target and start
*state = append(*state, (*choices)[i])
// Proceed to the next choice
backtrackSubsetSumI(i, target-(*choices)[i], state, choices, res)
// Backtrack: undo the choice and restore the previous state
*state = (*state)[:len(*state)-1]
}
}
/* Solve subset sum I */
func subsetSumI(nums []int, target int) [][]int {
state := make([]int, 0) // State (subset)
sort.Ints(nums) // Sort nums
start := 0 // Starting index for iteration
res := make([][]int, 0) // Result list (list of subsets)
backtrackSubsetSumI(start, target, &state, &nums, &res)
return res
}
/* Backtracking: subset sum I */
func backtrack(state: inout [Int], target: Int, choices: [Int], start: Int, res: inout [[Int]]) {
// Record a solution when the remaining target reaches zero
if target == 0 {
res.append(state)
return
}
// Iterate over all choices
// Pruning 2: iterate from start to avoid generating duplicate subsets
for i in choices.indices.dropFirst(start) {
// Pruning 1: exit the loop if this choice exceeds the remaining target
// The array is sorted, so later elements are at least as large and also exceed the remaining target
if target - choices[i] < 0 {
break
}
// Try: make a choice and update target and start
state.append(choices[i])
// Proceed to the next choice
backtrack(state: &state, target: target - choices[i], choices: choices, start: i, res: &res)
// Backtrack: undo the choice and restore the previous state
state.removeLast()
}
}
/* Solve subset sum I */
func subsetSumI(nums: [Int], target: Int) -> [[Int]] {
var state: [Int] = [] // State (subset)
let nums = nums.sorted() // Sort nums
let start = 0 // Starting index for iteration
var res: [[Int]] = [] // Result list (list of subsets)
backtrack(state: &state, target: target, choices: nums, start: start, res: &res)
return res
}
/* Backtracking: subset sum I */
function backtrack(state, target, choices, start, res) {
// Record a solution when the remaining target is zero, so the subset sum equals the original target
if (target === 0) {
res.push([...state]);
return;
}
// Iterate over all choices
// Pruning 2: iterate from start to avoid generating duplicate subsets
for (let i = start; i < choices.length; i++) {
// Pruning 1: exit the loop if the next choice exceeds the remaining target
// The array is sorted, so later elements are at least as large and would also exceed the remaining target
if (target - choices[i] < 0) {
break;
}
// Try: make a choice and update target and start
state.push(choices[i]);
// Proceed to the next choice
backtrack(state, target - choices[i], choices, i, res);
// Backtrack: undo the choice and restore the previous state
state.pop();
}
}
/* Solve subset sum I */
function subsetSumI(nums, target) {
const state = []; // State (subset)
nums.sort((a, b) => a - b); // Sort nums
const start = 0; // Starting index for iteration
const res = []; // Result list (list of subsets)
backtrack(state, target, nums, start, res);
return res;
}
/* Backtracking: subset sum I */
function backtrack(
state: number[],
target: number,
choices: number[],
start: number,
res: number[][]
): void {
// Record a solution when the subset reaches the original target (remaining target is 0)
if (target === 0) {
res.push([...state]);
return;
}
// Iterate over all choices
// Pruning 2: iterate from start to avoid generating duplicate subsets
for (let i = start; i < choices.length; i++) {
// Pruning 1: exit the loop if this choice would exceed the remaining target
// The array is sorted, so later elements are at least as large and would also exceed the remaining target
if (target - choices[i] < 0) {
break;
}
// Try: make a choice and update target and start
state.push(choices[i]);
// Proceed to the next choice
backtrack(state, target - choices[i], choices, i, res);
// Backtrack: undo the choice and restore the previous state
state.pop();
}
}
/* Solve subset sum I */
function subsetSumI(nums: number[], target: number): number[][] {
const state = []; // State (subset)
nums.sort((a, b) => a - b); // Sort nums
const start = 0; // Starting index for iteration
const res = []; // Result list (list of subsets)
backtrack(state, target, nums, start, res);
return res;
}
/* Backtracking: subset sum I */
void backtrack(
List<int> state,
int target,
List<int> choices,
int start,
List<List<int>> res,
) {
// Record a solution when the subset sum reaches the original target (the remaining target is 0)
if (target == 0) {
res.add(List.from(state));
return;
}
// Iterate over all choices
// Pruning 2: iterate from start to avoid generating duplicate subsets
for (int i = start; i < choices.length; i++) {
// Pruning 1: exit the loop if this choice exceeds the remaining target
// The array is sorted, so later elements are at least as large and also exceed the remaining target
if (target - choices[i] < 0) {
break;
}
// Try: make a choice and update target and start
state.add(choices[i]);
// Proceed to the next choice
backtrack(state, target - choices[i], choices, i, res);
// Backtrack: undo the choice and restore the previous state
state.removeLast();
}
}
/* Solve subset sum I */
List<List<int>> subsetSumI(List<int> nums, int target) {
List<int> state = []; // State (subset)
nums.sort(); // Sort nums
int start = 0; // Starting index for iteration
List<List<int>> res = []; // Result list (list of subsets)
backtrack(state, target, nums, start, res);
return res;
}
/* Backtracking: subset sum I */
fn backtrack(
state: &mut Vec<i32>,
target: i32,
choices: &[i32],
start: usize,
res: &mut Vec<Vec<i32>>,
) {
// Record a solution when the remaining target is zero
if target == 0 {
res.push(state.clone());
return;
}
// Iterate over all choices
// Pruning 2: iterate from start to avoid generating duplicate subsets
for i in start..choices.len() {
// Pruning 1: exit the loop if the next element exceeds the remaining target
// The array is sorted, so later elements are at least as large and also exceed the remaining target
if target - choices[i] < 0 {
break;
}
// Try: make a choice and update target and start
state.push(choices[i]);
// Proceed to the next choice
backtrack(state, target - choices[i], choices, i, res);
// Backtrack: undo the choice and restore the previous state
state.pop();
}
}
/* Solve subset sum I */
fn subset_sum_i(nums: &mut [i32], target: i32) -> Vec<Vec<i32>> {
let mut state = Vec::new(); // State (subset)
nums.sort(); // Sort nums
let start = 0; // Starting index for iteration
let mut res = Vec::new(); // Result list (list of subsets)
backtrack(&mut state, target, nums, start, &mut res);
res
}
/* Backtracking: subset sum I */
void backtrack(int target, int *choices, int choicesSize, int start) {
// Record a solution when the remaining target is 0
if (target == 0) {
for (int i = 0; i < stateSize; ++i) {
res[resSize][i] = state[i];
}
resColSizes[resSize++] = stateSize;
return;
}
// Iterate over all choices
// Pruning 2: iterate from start to avoid generating duplicate subsets
for (int i = start; i < choicesSize; i++) {
// Pruning 1: exit the loop if the choice exceeds the remaining target
// The array is sorted, so later elements are at least as large and also exceed the remaining target
if (target - choices[i] < 0) {
break;
}
// Try: make a choice and update target and start
state[stateSize] = choices[i];
stateSize++;
// Proceed to the next choice
backtrack(target - choices[i], choices, choicesSize, i);
// Backtrack: undo the choice and restore the previous state
stateSize--;
}
}
/* Solve subset sum I */
void subsetSumI(int *nums, int numsSize, int target) {
qsort(nums, numsSize, sizeof(int), cmp); // Sort nums
int start = 0; // Starting index for iteration
backtrack(target, nums, numsSize, start);
}
/* Backtracking: subset sum I */
fun backtrack(
state: MutableList<Int>,
target: Int,
choices: IntArray,
start: Int,
res: MutableList<MutableList<Int>?>
) {
// Record a solution when the subset reaches the original target (remaining target is 0)
if (target == 0) {
res.add(state.toMutableList())
return
}
// Iterate over all choices
// Pruning 2: iterate from start to avoid generating duplicate subsets
for (i in start..<choices.size) {
// Pruning 1: exit the loop if this choice would exceed the remaining target
// The array is sorted, so later elements are at least as large and would also exceed the remaining target
if (target - choices[i] < 0) {
break
}
// Try: make a choice and update target and start
state.add(choices[i])
// Proceed to the next choice
backtrack(state, target - choices[i], choices, i, res)
// Backtrack: undo the choice and restore the previous state
state.removeAt(state.size - 1)
}
}
/* Solve subset sum I */
fun subsetSumI(nums: IntArray, target: Int): MutableList<MutableList<Int>?> {
val state = mutableListOf<Int>() // State (subset)
nums.sort() // Sort nums
val start = 0 // Starting index for iteration
val res = mutableListOf<MutableList<Int>?>() // Result list (list of subsets)
backtrack(state, target, nums, start, res)
return res
}
### Backtracking: subset sum I ###
def backtrack(state, target, choices, start, res)
# Record a solution when the remaining target reaches zero
if target.zero?
res << state.dup
return
end
# Iterate over all choices
# Pruning 2: iterate from start to avoid generating duplicate subsets
for i in start...choices.length
# Pruning 1: exit the loop if this choice would exceed the remaining target
# The array is sorted, so later elements are at least as large and would also exceed the remaining target
break if target - choices[i] < 0
# Try: make a choice and update target and start
state << choices[i]
# Proceed to the next choice
backtrack(state, target - choices[i], choices, i, res)
# Backtrack: undo the choice and restore the previous state
state.pop
end
end
### Solve subset sum I ###
def subset_sum_i(nums, target)
state = [] # State (subset)
nums.sort! # Sort nums
start = 0 # Starting index for iteration
res = [] # Result list (list of subsets)
backtrack(state, target, nums, start, res)
res
end
Visualize execution
Figure 13-12 shows the complete backtracking process for input \([3, 4, 5]\) and target \(9\).
Figure 13-12 Backtracking for subset sum I
Description of Figure 13-12: Subset sum I: zeroing the remaining target and index-order pruning
Starting from target 9, subtract candidates level by level while combining start = i with a break when a candidate exceeds the remaining target to output [3, 3, 3] and [4, 5].
The input consists of the sorted positive integer array choices = [3, 4, 5] (indices 0, 1, 2) and initial target = 9; elements may be chosen repeatedly, and combinations ignore order. The number inside each circular node shows the remaining target balance (9 minus the current prefix sum), reaching a valid subset when reduced to 0.
Upon entering a call, if the remaining target is 0, record the current combination and return to the parent call so its loop can continue; otherwise iterate through candidates choices[i] starting from index start, subtract the chosen value from the remaining target, and recurse to the next level. Passing start = i downward allows choosing the current element again while skipping earlier indices (the index-order pruning marked by black scissors in the figure).
Because the candidates are sorted in ascending order, within i ≥ start, encountering the first candidate greater than the remaining target triggers an immediate break after comparison, ending the current loop; neither that candidate nor any larger ones after it are entered recursively. Red scissors in the figure mark these out-of-range branches.
The figure contains 10 circular nodes with nonnegative remaining targets. The table below lists by prefix the remaining target, the restrictions shown in the figure, and the actual continuation; the remaining target 1 under [4, 4] is left unexpanded in the figure, and its subsequent break is supplied from the code rules.
| Current prefix | Remaining target | Available choices | Restriction or termination in figure | Actual continuation |
|---|---|---|---|---|
| [] | 9 | 3, 4, 5 | None | Remaining targets after choosing are 6, 5, and 4, respectively |
| [3] | 6 | 3, 4, 5 | None | Remaining targets after choosing are 3, 2, and 1, respectively |
| [3,3] | 3 | 3 | 4 and 5 exceed remaining target | Choose 3 to reach 0; break upon reaching 4 |
| [3,3,3] | 0 | None | No further choices | Record [3, 3, 3] |
| [3,4] | 2 | None | 3 is at an earlier index; 4 and 5 exceed remaining target | Immediate break starting at 4 |
| [3,5] | 1 | None | 3 and 4 are at earlier indices; 5 exceeds remaining target | Immediate break starting at 5 |
| [4] | 5 | 4, 5 | 3 is at an earlier index | Choose 4 to reach 1; choose 5 to reach 0 |
| [4,4] | 1 | None | Continuation not expanded in figure | By the code rules, immediate break starting at 4 |
| [4,5] | 0 | None | No further choices | Record [4, 5] |
| [5] | 4 | None | 3 and 4 are at earlier indices; 5 exceeds remaining target | Immediate break starting at 5 |
The two paths that reduce the remaining target to 0 are 9 → 6 → 3 → 0 and 9 → 5 → 0, yielding [3, 3, 3] and [4, 5], respectively.
13.3.2 Duplicate elements¶
Question
Given an array of positive integers nums and a positive target integer target, find all combinations whose elements sum to target. The array may contain duplicate elements, and each element may be chosen only once. Return the combinations as a list containing no duplicates.
Unlike the previous problem, the input may contain duplicate elements, which introduces a new issue. For array \([4, \hat{4}, 5]\) and target \(9\), for example, the existing code produces \([4, 5], [\hat{4}, 5]\): duplicate subsets.
These duplicates occur because equal elements are tried more than once in a single round. In Figure 13-13, the first round has three choices, two of which are \(4\). They generate duplicate branches and therefore duplicate subsets. The two occurrences of \(4\) in the second round cause the same problem.
Figure 13-13 Duplicate subsets caused by equal elements
Description of Figure 13-13: Equal candidates introduce new duplicate combinations
Two elements of value 4 in the candidate array create duplicate subset branches with identical contents within the same round of choices.
The input array is choices = [4, 4, 5] at indices 0, 1, and 2. Below, "first 4" and "second 4" distinguish indices 0 and 1; the figure places a hat over the second 4, though both have numeric value 4. Subset sum II requires using each index at most once and producing no duplicate subsets. This figure initially reuses the subset sum I selection rule—passing start = i to the next round so the current index may be chosen again—to illustrate the problem caused by equal candidates.
At the top is choices. Starting from the empty state, the two-level partial search tree chooses the first 4, the second 4, or 5 in the first round; in the second round, it tries all three candidates again only under [first 4, …]. In both places, the third branch is labeled only +5 without writing out its prefix.
The first gray arc connects [first 4, …] with [second 4, …], and the second connects [first 4, first 4, …] with [first 4, second 4, …], both labeled "Duplicate subsets". The first pair shares the numeric prefix [4, …], and the second pair shares [4, 4, …]. Moreover, choosing the first 4 again reuses index 0, which is itself disallowed under the rules of subset sum II.
Eliminating duplicates in subset sum II requires both forbidding reuse of the same index along a path and trying equal-valued candidates only once within the same round, while still allowing the two 4s at distinct indices to be chosen in different rounds along the same path.
1. Pruning equal elements¶
To solve this, try each value only once in each round. The implementation uses the fact that equal elements are adjacent in a sorted array. Within a round, if an element equals the preceding element, that value has already been tried, so skip the current element.
In addition, each array element may be chosen only once. Fortunately, start can enforce this constraint too: after choosing \(x_{i}\), begin the next round at index \(i + 1\). This both eliminates duplicate subsets and prevents reusing an element.
2. Code implementation¶
def backtrack(
state: list[int], target: int, choices: list[int], start: int, res: list[list[int]]
):
"""Backtracking: subset sum II"""
# Record a solution when the remaining target is zero
if target == 0:
res.append(list(state))
return
# Iterate over all choices
# Pruning 2: iterate from start to avoid generating duplicate subsets
# Pruning 3: start after the previously chosen index to avoid choosing the same element again
for i in range(start, len(choices)):
# Pruning 1: exit the loop if this choice exceeds the remaining target
# The array is sorted, so later elements are at least as large and also exceed the remaining target
if target - choices[i] < 0:
break
# Pruning 4: if this element equals its left neighbor at the same search depth, the branch is a duplicate; skip it
if i > start and choices[i] == choices[i - 1]:
continue
# Try: make a choice and update target and start
state.append(choices[i])
# Proceed to the next choice
backtrack(state, target - choices[i], choices, i + 1, res)
# Backtrack: undo the choice and restore the previous state
state.pop()
def subset_sum_ii(nums: list[int], target: int) -> list[list[int]]:
"""Solve subset sum II"""
state = [] # State (subset)
nums.sort() # Sort nums
start = 0 # Starting index for iteration
res = [] # Result list (list of subsets)
backtrack(state, target, nums, start, res)
return res
/* Backtracking: subset sum II */
void backtrack(vector<int> &state, int target, vector<int> &choices, int start, vector<vector<int>> &res) {
// Record a solution when the remaining target reaches 0
if (target == 0) {
res.push_back(state);
return;
}
// Iterate over all choices
// Pruning 2: iterate from start to avoid generating duplicate subsets
// Pruning 3: iterate from start to avoid choosing the same element again
for (int i = start; i < choices.size(); i++) {
// Pruning 1: exit the loop if this choice exceeds the remaining target
// The array is sorted, so later elements are at least as large and also exceed the remaining target
if (target - choices[i] < 0) {
break;
}
// Pruning 4: if this element equals its left neighbor at the same search depth, the branch is a duplicate; skip it
if (i > start && choices[i] == choices[i - 1]) {
continue;
}
// Try: make a choice and update target and start
state.push_back(choices[i]);
// Proceed to the next choice
backtrack(state, target - choices[i], choices, i + 1, res);
// Backtrack: undo the choice and restore the previous state
state.pop_back();
}
}
/* Solve subset sum II */
vector<vector<int>> subsetSumII(vector<int> &nums, int target) {
vector<int> state; // State (subset)
sort(nums.begin(), nums.end()); // Sort nums
int start = 0; // Starting index for iteration
vector<vector<int>> res; // Result list (list of subsets)
backtrack(state, target, nums, start, res);
return res;
}
/* Backtracking: subset sum II */
void backtrack(List<Integer> state, int target, int[] choices, int start, List<List<Integer>> res) {
// Record a solution when the remaining target is zero, so the subset sums to the original target
if (target == 0) {
res.add(new ArrayList<>(state));
return;
}
// Iterate over all choices
// Pruning 2: iterate from start to avoid generating duplicate subsets
// Pruning 3: iterate from start to avoid choosing the same element again
for (int i = start; i < choices.length; i++) {
// Pruning 1: exit the loop if the next element exceeds the remaining target
// The array is sorted, so later elements are at least as large and also exceed the remaining target
if (target - choices[i] < 0) {
break;
}
// Pruning 4: if this element equals its left neighbor at the same search depth, the branch is a duplicate; skip it
if (i > start && choices[i] == choices[i - 1]) {
continue;
}
// Try: make a choice and update target and start
state.add(choices[i]);
// Proceed to the next choice
backtrack(state, target - choices[i], choices, i + 1, res);
// Backtrack: undo the choice and restore the previous state
state.remove(state.size() - 1);
}
}
/* Solve subset sum II */
List<List<Integer>> subsetSumII(int[] nums, int target) {
List<Integer> state = new ArrayList<>(); // State (subset)
Arrays.sort(nums); // Sort nums
int start = 0; // Starting index for iteration
List<List<Integer>> res = new ArrayList<>(); // Result list (list of subsets)
backtrack(state, target, nums, start, res);
return res;
}
/* Backtracking: subset sum II */
void Backtrack(List<int> state, int target, int[] choices, int start, List<List<int>> res) {
// Record a solution when the subset reaches the original target (remaining target is 0)
if (target == 0) {
res.Add(new List<int>(state));
return;
}
// Iterate over all choices
// Pruning 2: iterate from start to avoid generating duplicate subsets
// Pruning 3: start after the previously chosen index to avoid choosing the same element again
for (int i = start; i < choices.Length; i++) {
// Pruning 1: exit the loop if this choice would exceed the remaining target
// The array is sorted, so later elements are at least as large and would also exceed the remaining target
if (target - choices[i] < 0) {
break;
}
// Pruning 4: if this element equals its left neighbor at the same search depth, the branch is a duplicate; skip it
if (i > start && choices[i] == choices[i - 1]) {
continue;
}
// Try: make a choice and update target and start
state.Add(choices[i]);
// Proceed to the next choice
Backtrack(state, target - choices[i], choices, i + 1, res);
// Backtrack: undo the choice and restore the previous state
state.RemoveAt(state.Count - 1);
}
}
/* Solve subset sum II */
List<List<int>> SubsetSumII(int[] nums, int target) {
List<int> state = []; // State (subset)
Array.Sort(nums); // Sort nums
int start = 0; // Starting index for iteration
List<List<int>> res = []; // Result list (list of subsets)
Backtrack(state, target, nums, start, res);
return res;
}
/* Backtracking: subset sum II */
func backtrackSubsetSumII(start, target int, state, choices *[]int, res *[][]int) {
// Record a solution when the subset reaches the original target sum (remaining target is zero)
if target == 0 {
newState := append([]int{}, *state...)
*res = append(*res, newState)
return
}
// Iterate over all choices
// Pruning 2: iterate from start to avoid generating duplicate subsets
// Pruning 3: start after the previously chosen index to avoid choosing the same element again
for i := start; i < len(*choices); i++ {
// Pruning 1: exit the loop if this choice exceeds the remaining target
// The array is sorted, so later elements are at least as large and also exceed the remaining target
if target-(*choices)[i] < 0 {
break
}
// Pruning 4: if this element equals its left neighbor at the same search depth, the branch is a duplicate; skip it
if i > start && (*choices)[i] == (*choices)[i-1] {
continue
}
// Try: make a choice and update target and start
*state = append(*state, (*choices)[i])
// Proceed to the next choice
backtrackSubsetSumII(i+1, target-(*choices)[i], state, choices, res)
// Backtrack: undo the choice and restore the previous state
*state = (*state)[:len(*state)-1]
}
}
/* Solve subset sum II */
func subsetSumII(nums []int, target int) [][]int {
state := make([]int, 0) // State (subset)
sort.Ints(nums) // Sort nums
start := 0 // Starting index for iteration
res := make([][]int, 0) // Result list (list of subsets)
backtrackSubsetSumII(start, target, &state, &nums, &res)
return res
}
/* Backtracking: subset sum II */
func backtrack(state: inout [Int], target: Int, choices: [Int], start: Int, res: inout [[Int]]) {
// Record a solution when the remaining target reaches zero
if target == 0 {
res.append(state)
return
}
// Iterate over all choices
// Pruning 2: iterate from start to avoid generating duplicate subsets
// Pruning 3: start after the previously chosen index to avoid choosing the same element again
for i in choices.indices.dropFirst(start) {
// Pruning 1: exit the loop if this choice exceeds the remaining target
// The array is sorted, so later elements are at least as large and also exceed the remaining target
if target - choices[i] < 0 {
break
}
// Pruning 4: if this element equals its left neighbor at the same search depth, the branch is a duplicate; skip it
if i > start, choices[i] == choices[i - 1] {
continue
}
// Try: make a choice and update target and start
state.append(choices[i])
// Proceed to the next choice
backtrack(state: &state, target: target - choices[i], choices: choices, start: i + 1, res: &res)
// Backtrack: undo the choice and restore the previous state
state.removeLast()
}
}
/* Solve subset sum II */
func subsetSumII(nums: [Int], target: Int) -> [[Int]] {
var state: [Int] = [] // State (subset)
let nums = nums.sorted() // Sort nums
let start = 0 // Starting index for iteration
var res: [[Int]] = [] // Result list (list of subsets)
backtrack(state: &state, target: target, choices: nums, start: start, res: &res)
return res
}
/* Backtracking: subset sum II */
function backtrack(state, target, choices, start, res) {
// Record a solution when the remaining target is zero, so the subset sum equals the original target
if (target === 0) {
res.push([...state]);
return;
}
// Iterate over all choices
// Pruning 2: iterate from start to avoid generating duplicate subsets
// Pruning 3: start after the previously chosen index to avoid choosing the same element again
for (let i = start; i < choices.length; i++) {
// Pruning 1: exit the loop if the next choice exceeds the remaining target
// The array is sorted, so later elements are at least as large and would also exceed the remaining target
if (target - choices[i] < 0) {
break;
}
// Pruning 4: if this element equals its left neighbor at the same search depth, the branch is a duplicate; skip it
if (i > start && choices[i] === choices[i - 1]) {
continue;
}
// Try: make a choice and update target and start
state.push(choices[i]);
// Proceed to the next choice
backtrack(state, target - choices[i], choices, i + 1, res);
// Backtrack: undo the choice and restore the previous state
state.pop();
}
}
/* Solve subset sum II */
function subsetSumII(nums, target) {
const state = []; // State (subset)
nums.sort((a, b) => a - b); // Sort nums
const start = 0; // Starting index for iteration
const res = []; // Result list (list of subsets)
backtrack(state, target, nums, start, res);
return res;
}
/* Backtracking: subset sum II */
function backtrack(
state: number[],
target: number,
choices: number[],
start: number,
res: number[][]
): void {
// Record a solution when the subset reaches the original target (remaining target is 0)
if (target === 0) {
res.push([...state]);
return;
}
// Iterate over all choices
// Pruning 2: iterate from start to avoid generating duplicate subsets
// Pruning 3: start after the previously chosen index to avoid choosing the same element again
for (let i = start; i < choices.length; i++) {
// Pruning 1: exit the loop if this choice would exceed the remaining target
// The array is sorted, so later elements are at least as large and would also exceed the remaining target
if (target - choices[i] < 0) {
break;
}
// Pruning 4: if this element equals its left neighbor at the same search depth, the branch is a duplicate; skip it
if (i > start && choices[i] === choices[i - 1]) {
continue;
}
// Try: make a choice and update target and start
state.push(choices[i]);
// Proceed to the next choice
backtrack(state, target - choices[i], choices, i + 1, res);
// Backtrack: undo the choice and restore the previous state
state.pop();
}
}
/* Solve subset sum II */
function subsetSumII(nums: number[], target: number): number[][] {
const state = []; // State (subset)
nums.sort((a, b) => a - b); // Sort nums
const start = 0; // Starting index for iteration
const res = []; // Result list (list of subsets)
backtrack(state, target, nums, start, res);
return res;
}
/* Backtracking: subset sum II */
void backtrack(
List<int> state,
int target,
List<int> choices,
int start,
List<List<int>> res,
) {
// Record a solution when the subset sum reaches the original target (the remaining target is 0)
if (target == 0) {
res.add(List.from(state));
return;
}
// Iterate over all choices
// Pruning 2: iterate from start to avoid generating duplicate subsets
// Pruning 3: start after the previously chosen index to avoid choosing the same element again
for (int i = start; i < choices.length; i++) {
// Pruning 1: exit the loop if this choice exceeds the remaining target
// The array is sorted, so later elements are at least as large and also exceed the remaining target
if (target - choices[i] < 0) {
break;
}
// Pruning 4: if this element equals its left neighbor at the same search depth, the branch is a duplicate; skip it
if (i > start && choices[i] == choices[i - 1]) {
continue;
}
// Try: make a choice and update target and start
state.add(choices[i]);
// Proceed to the next choice
backtrack(state, target - choices[i], choices, i + 1, res);
// Backtrack: undo the choice and restore the previous state
state.removeLast();
}
}
/* Solve subset sum II */
List<List<int>> subsetSumII(List<int> nums, int target) {
List<int> state = []; // State (subset)
nums.sort(); // Sort nums
int start = 0; // Starting index for iteration
List<List<int>> res = []; // Result list (list of subsets)
backtrack(state, target, nums, start, res);
return res;
}
/* Backtracking: subset sum II */
fn backtrack(
state: &mut Vec<i32>,
target: i32,
choices: &[i32],
start: usize,
res: &mut Vec<Vec<i32>>,
) {
// Record a solution when the remaining target is zero
if target == 0 {
res.push(state.clone());
return;
}
// Iterate over all choices
// Pruning 2: iterate from start to avoid generating duplicate subsets
// Pruning 3: iterate from start to avoid choosing the same element again
for i in start..choices.len() {
// Pruning 1: exit the loop if the next element exceeds the remaining target
// The array is sorted, so later elements are at least as large and also exceed the remaining target
if target - choices[i] < 0 {
break;
}
// Pruning 4: if this element equals its left neighbor at the same search depth, the branch is a duplicate; skip it
if i > start && choices[i] == choices[i - 1] {
continue;
}
// Try: make a choice and update target and start
state.push(choices[i]);
// Proceed to the next choice
backtrack(state, target - choices[i], choices, i + 1, res);
// Backtrack: undo the choice and restore the previous state
state.pop();
}
}
/* Solve subset sum II */
fn subset_sum_ii(nums: &mut [i32], target: i32) -> Vec<Vec<i32>> {
let mut state = Vec::new(); // State (subset)
nums.sort(); // Sort nums
let start = 0; // Starting index for iteration
let mut res = Vec::new(); // Result list (list of subsets)
backtrack(&mut state, target, nums, start, &mut res);
res
}
/* Backtracking: subset sum II */
void backtrack(int target, int *choices, int choicesSize, int start) {
// Record a solution when the remaining target is 0
if (target == 0) {
for (int i = 0; i < stateSize; i++) {
res[resSize][i] = state[i];
}
resColSizes[resSize++] = stateSize;
return;
}
// Iterate over all choices
// Pruning 2: iterate from start to avoid generating duplicate subsets
// Pruning 3: iterate from start to avoid choosing the same element again
for (int i = start; i < choicesSize; i++) {
// Pruning 1: skip this choice if it exceeds the remaining target
if (target - choices[i] < 0) {
continue;
}
// Pruning 4: if this element equals its left neighbor at the same search depth, the branch is a duplicate; skip it
if (i > start && choices[i] == choices[i - 1]) {
continue;
}
// Try: make a choice and update target and start
state[stateSize] = choices[i];
stateSize++;
// Proceed to the next choice
backtrack(target - choices[i], choices, choicesSize, i + 1);
// Backtrack: undo the choice and restore the previous state
stateSize--;
}
}
/* Solve subset sum II */
void subsetSumII(int *nums, int numsSize, int target) {
// Sort nums
qsort(nums, numsSize, sizeof(int), cmp);
// Start backtracking
backtrack(target, nums, numsSize, 0);
}
/* Backtracking: subset sum II */
fun backtrack(
state: MutableList<Int>,
target: Int,
choices: IntArray,
start: Int,
res: MutableList<MutableList<Int>?>
) {
// Record a solution when the subset reaches the original target (remaining target is 0)
if (target == 0) {
res.add(state.toMutableList())
return
}
// Iterate over all choices
// Pruning 2: iterate from start to avoid generating duplicate subsets
// Pruning 3: start after the previously chosen index to avoid choosing the same element again
for (i in start..<choices.size) {
// Pruning 1: exit the loop if this choice would exceed the remaining target
// The array is sorted, so later elements are at least as large and would also exceed the remaining target
if (target - choices[i] < 0) {
break
}
// Pruning 4: if this element equals its left neighbor at the same search depth, the branch is a duplicate; skip it
if (i > start && choices[i] == choices[i - 1]) {
continue
}
// Try: make a choice and update target and start
state.add(choices[i])
// Proceed to the next choice
backtrack(state, target - choices[i], choices, i + 1, res)
// Backtrack: undo the choice and restore the previous state
state.removeAt(state.size - 1)
}
}
/* Solve subset sum II */
fun subsetSumII(nums: IntArray, target: Int): MutableList<MutableList<Int>?> {
val state = mutableListOf<Int>() // State (subset)
nums.sort() // Sort nums
val start = 0 // Starting index for iteration
val res = mutableListOf<MutableList<Int>?>() // Result list (list of subsets)
backtrack(state, target, nums, start, res)
return res
}
### Backtracking: subset sum II ###
def backtrack(state, target, choices, start, res)
# Record a solution when the remaining target reaches zero
if target.zero?
res << state.dup
return
end
# Iterate over all choices
# Pruning 2: iterate from start to avoid generating duplicate subsets
# Pruning 3: start after the previously chosen index to avoid choosing the same element again
for i in start...choices.length
# Pruning 1: exit the loop if this choice would exceed the remaining target
# The array is sorted, so later elements are at least as large and would also exceed the remaining target
break if target - choices[i] < 0
# Pruning 4: if this element equals its left neighbor at the same search depth, the branch is a duplicate; skip it
next if i > start && choices[i] == choices[i - 1]
# Try: make a choice and update target and start
state << choices[i]
# Proceed to the next choice
backtrack(state, target - choices[i], choices, i + 1, res)
# Backtrack: undo the choice and restore the previous state
state.pop
end
end
### Solve subset sum II ###
def subset_sum_ii(nums, target)
state = [] # State (subset)
nums.sort! # Sort nums
start = 0 # Starting index for iteration
res = [] # Result list (list of subsets)
backtrack(state, target, nums, start, res)
res
end
Visualize execution
Figure 13-14 shows backtracking for array \([4, 4, 5]\) and target \(9\), including four types of pruning. Follow the illustration alongside the code comments to understand the full search and how each pruning rule works.
Figure 13-14 Backtracking for subset sum II
Description of Figure 13-14: Four pruning conditions for subset sum II
Search the sorted array [4, 4, 5] for subsets summing to 9, combining four pruning conditions to keep only the unique solution [4, 5].
The input array is choices = [4, 4, 5] at indices 0, 1, and 2. Below, "first 4" and "second 4" distinguish indices 0 and 1; the figure places a hat over the second 4, though both have numeric value 4. The array is sorted and target = 9; numbers inside the circles show the remaining target.
Each index may be used at most once, and subsets ignore order. After selecting index i, the next round begins at start = i + 1, enforcing two rules at once: neither going back to an earlier index (Pruning 2) nor reusing the current index (Pruning 3).
When trying the second 4 at the root, its index i = 1 is greater than start = 0, and its value equals the previous candidate’s value, triggering same-round deduplication (Pruning 4). After entering [first 4], the new call has start = 1; now the second 4 has i = 1 equal to start rather than i > start, so it remains selectable. Choosing it leaves a remaining target of 1, and the only candidate afterward is 5, which exceeds the remaining target and triggers an immediate break under Pruning 1.
Below, the "Meanings of the four pruning conditions" table matches the four colors of scissors in the figure, and the next table lists each prefix and candidate in turn. None of the pruned branches is entered recursively. Pruning 2 and Pruning 3 are skipped directly via start = i + 1—the code never loops over those candidates individually, though the figure draws them for comparison; under [first 4, second 4], choosing the first 4 again is labeled as returning to an earlier index (Pruning 2) in the figure, while its index 0 is also already on the path.
| Legend | Excluded case |
|---|---|
| Pruning 1 (red) | Selecting the candidate pushes the sum past 9, making remaining target negative |
| Pruning 2 (blue) | Going back to an earlier index produces a duplicate combination in a different order |
| Pruning 3 (purple) | Reusing the current array index that was just selected |
| Pruning 4 (cyan) | Trying another candidate with the same value within the same round |
| Prefix and illustrated candidate | Remaining target before candidate | Outcome or pruning reason |
|---|---|---|
| []: candidate first 4 | 9 | Kept, remaining target 5 |
| []: candidate second 4 | 9 | Duplicate value in round, Pruning 4 |
| []: candidate 5 | 9 | Kept, remaining target 4 |
| [first 4]: candidate first 4 | 5 | Reuses current index, Pruning 3 |
| [first 4]: candidate second 4 | 5 | Distinct index, selectable, remaining target 1 |
| [first 4]: candidate 5 | 5 | Remaining target 0, record [4, 5] |
| [first 4, second 4]: candidate first 4 | 1 | Returns to earlier index, shown as Pruning 2 |
| [first 4, second 4]: candidate second 4 | 1 | Reuses current index, Pruning 3 |
| [first 4, second 4]: candidate 5 | 1 | Exceeds remaining target, Pruning 1 |
| [5]: candidates first 4, second 4 | 4 | Returns to earlier index, Pruning 2 |
| [5]: candidate 5 | 4 | Reuses current index, Pruning 3 |
The only path that reduces the remaining target to 0 picks the first 4 and then 5, yielding [4, 5].