Skip to content

Commit c6c0744

Browse files
authored
Create 0039-combination-sum.rs
1 parent cf50630 commit c6c0744

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

rust/0039-combination-sum.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
impl Solution {
2+
fn dfs(candidates: &[i32], target: i32, result: &mut Vec<Vec<i32>>, curr: &mut Vec<i32>) {
3+
let sum: i32 = curr.iter().sum();
4+
if sum == target {
5+
result.push(curr.to_owned());
6+
return;
7+
} else if sum > target {
8+
return;
9+
}
10+
11+
for (i, &c) in candidates.iter().enumerate() {
12+
curr.push(c);
13+
Self::dfs(&candidates[i..], target, result, curr);
14+
curr.pop();
15+
}
16+
}
17+
18+
pub fn combination_sum(candidates: Vec<i32>, target: i32) -> Vec<Vec<i32>> {
19+
let (mut result, mut curr) = (vec![], vec![]);
20+
Self::dfs(&candidates, target, &mut result, &mut curr);
21+
22+
result
23+
}
24+
}

0 commit comments

Comments
 (0)