Skip to content

Commit cf0243f

Browse files
committed
feat(backtracking): add 39_combination_sum.rs
1 parent f5437ef commit cf0243f

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,3 +145,4 @@ so that you can use `just tf TEST` command to test.
145145
| Problem | Difficulty | Solution |
146146
| - | - | - |
147147
| 78. Subsets | Medium | [78_subsets.rs](./tests/78_subsets.rs) |
148+
| 39. Combination Sum | Medium | [39_combination_sum.rs](./tests/39_combination_sum.rs) |

tests/39_combination_sum.rs

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// 39. Combination Sum
2+
// https://leetcode.com/problems/combination-sum/description/
3+
// Topics: Backtracking.
4+
// Difficulty: Medium.
5+
6+
#[test]
7+
fn test_39_combination_sum() {}
8+
9+
#[derive(Debug)]
10+
pub struct Solution;
11+
12+
// ---------------------------------
13+
// copy to leetcode starts from here
14+
// ---------------------------------
15+
16+
impl Solution {
17+
pub fn combination_sum(candidates: Vec<i32>, target: i32) -> Vec<Vec<i32>> {
18+
let mut result: Vec<Vec<i32>> = vec![];
19+
let mut current: Vec<i32> = vec![];
20+
find_combinations(0, target, candidates.as_ref(), &mut current, &mut result);
21+
result
22+
}
23+
}
24+
25+
fn find_combinations(
26+
index: usize,
27+
target: i32,
28+
candidates: &[i32],
29+
current: &mut Vec<i32>,
30+
result: &mut Vec<Vec<i32>>,
31+
) {
32+
if target == 0 {
33+
result.push(current.to_vec());
34+
return;
35+
}
36+
37+
for i in index..candidates.len() {
38+
if candidates[i] <= target {
39+
current.push(candidates[i]);
40+
find_combinations(i, target - candidates[i], candidates, current, result);
41+
current.pop();
42+
}
43+
}
44+
}

0 commit comments

Comments
 (0)