-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0377_combination_sum_iv.rs
More file actions
43 lines (37 loc) · 1.04 KB
/
Copy paths0377_combination_sum_iv.rs
File metadata and controls
43 lines (37 loc) · 1.04 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
#![allow(unused)]
pub struct Solution {}
use std::collections::HashMap;
impl Solution {
// O(n) O(n)
pub fn combination_sum4(nums: Vec<i32>, target: i32) -> i32 {
fn helper(map: &mut HashMap<i32, i32>, nums: &Vec<i32>, target: i32) -> i32 {
if target == 0 {
return 1;
} else if target < 0 {
return 0;
}
let mut sum = 0;
for &num in nums.iter() {
if map.contains_key(&(target - num)) {
sum += *map.get(&(target - num)).unwrap();
} else {
let ret = helper(map, nums, target - num);
map.insert(target - num, ret);
sum += ret;
}
}
return sum;
}
// DP
let mut map = HashMap::new();
helper(&mut map, &nums, target)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_377() {
assert_eq!(Solution::combination_sum4(vec![1, 2, 3], 4), 7);
}
}