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
51
52
53
54
55
56
57
| struct Solution;
// @lc code=start
impl Solution {
/// ## 解题思路
/// - 迭代法
/// 1. 将数组排序;
/// 2. 依次从candidates中取出一个数,如果该数小于当前target,则加入临时数组中;
pub fn combination_sum(candidates: Vec<i32>, target: i32) -> Vec<Vec<i32>> {
///
fn combine_sum(candidates: &[i32], left: i32, sub: &[i32], res: &mut Vec<Vec<i32>>) {
match left {
n if n < 0 => return,
0 => {
res.push(sub.to_vec());
return;
}
_ => {
candidates
.iter()
.filter(|&c| *c <= left)
.enumerate()
.for_each(|(i, c)| {
let mut s = sub.to_vec();
s.push(*c);
combine_sum(&candidates[i..], left - c, &s, res);
});
}
}
}
let mut res: Vec<Vec<i32>> = vec![];
let mut c = candidates.to_vec();
c.sort();
combine_sum(&c, target, &vec![], &mut res);
res
}
}
// @lc code=end
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test() {
assert_eq!(
Solution::combination_sum(vec![2, 3, 6, 7], 7),
vec![vec![2, 2, 3], vec![7],]
);
assert_eq!(
Solution::combination_sum(vec![2, 3, 5], 8),
vec![vec![2, 2, 2, 2], vec![2, 3, 3], vec![3, 5]]
);
}
}
|