-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0040_combination_sum_ii.rs
More file actions
50 lines (45 loc) · 1.39 KB
/
s0040_combination_sum_ii.rs
File metadata and controls
50 lines (45 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#![allow(unused)]
pub struct Solution {}
impl Solution {
fn backtrack(candidates: &Vec<i32>, ans: &mut Vec<Vec<i32>>, cur: &mut Vec<i32>, start: usize, target: i32) {
if target == 0 {
ans.push(cur.clone());
return;
} else if target < 0 {
return;
}
for i in start..candidates.len() {
// skip dups
if i > start && candidates[i] == candidates[i-1] {
continue;
}
cur.push(candidates[i]);
Self::backtrack(candidates, ans, cur, i+1, target - candidates[i]);
cur.pop();
}
}
// O(N^(T/M+ 1)) O(T/M)
// Let N be the number of candidates, T be the target value, and M be the minimal value
// among the candidates.
pub fn combination_sum2(mut candidates: Vec<i32>, target: i32) -> Vec<Vec<i32>> {
let mut ans = Vec::new();
candidates.sort();
Self::backtrack(&candidates, &mut ans, &mut Vec::new(), 0, target);
ans
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_40() {
// assert_eq!(
// Solution::combination_sum2(vec![10,1,2,7,6,1,5], 8),
// vec![vec![1, 1, 6], vec![1, 2, 5], vec![1, 7], vec![2, 6]]
// );
assert_eq!(
Solution::combination_sum2(vec![2, 5, 2, 1, 2], 5),
vec![vec![1, 2, 2], vec![5]]
);
}
}