Skip to content

Commit 6cee9b8

Browse files
committed
src/bin/coin-change.rs
1 parent 851bed4 commit 6cee9b8

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

src/bin/coin-change.rs

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
fn main() {
2+
println!("{}", Solution::coin_change(vec![1, 2, 5], 11));
3+
println!("{}", Solution::coin_change(vec![1], 1));
4+
println!("{}", Solution::coin_change(vec![1, 2, 5], 100));
5+
}
6+
7+
struct Solution;
8+
9+
impl Solution {
10+
pub fn coin_change(coins: Vec<i32>, amount: i32) -> i32 {
11+
if amount == 0 { return 0; }
12+
13+
let mut h = std::collections::HashMap::new();
14+
15+
Self::f(&coins[..], &mut h, amount)
16+
}
17+
18+
fn f(coins: &[i32], h: &mut std::collections::HashMap<i32, i32>, amount: i32) -> i32 {
19+
let mut num = -1;
20+
21+
for &i in coins {
22+
if i > amount {
23+
continue;
24+
} else if i == amount {
25+
return 1;
26+
}
27+
28+
let x = if let Some(x) = h.get(&(amount - i)) {
29+
*x
30+
} else {
31+
Self::f(coins, h, amount - i)
32+
};
33+
34+
if x == -1 {
35+
continue;
36+
}
37+
38+
if num == -1 {
39+
num = x + 1;
40+
} else {
41+
num = num.min(x + 1);
42+
}
43+
}
44+
45+
h.insert(amount, num);
46+
47+
num
48+
}
49+
}

0 commit comments

Comments
 (0)