#39
Medium Algorithms Combination sum
Array Backtracking
76.1% acceptance
Jan 12, 2026
20856
532
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
Solution
Rust
Time O(2^n)
Space O(n)
impl Solution {
pub fn combination_sum(candidates: Vec<i32>, target: i32) -> Vec<Vec<i32>> {
let mut result = Vec::new();
let mut current = Vec::new();
Self::helper39(&candidates, target, 0, &mut current, &mut result);
result
}
fn helper39(
candidates: &Vec<i32>,
target: i32,
start: usize,
current: &mut Vec<i32>,
result: &mut Vec<Vec<i32>>,
) {
if target == 0 {
result.push(current.clone());
return;
}
if target < 0 {
return;
}
for i in start..candidates.len() {
current.push(candidates[i]);
// Can reuse the same element, so pass i instead of i+1
Self::helper39(candidates, target - candidates[i], i, current, result);
current.pop();
}
}
}