Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 52684ec

Browse files
author
guangsheng.li01
committed
Solved 0322
1 parent 909fc98 commit 52684ec

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

‎src/a0322_coin_change.rs

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/*
2+
* [0322] coin-change
3+
*/
4+
5+
pub struct Solution {}
6+
7+
use std::cmp::min;
8+
use std::collections::HashMap;
9+
use std::i32::MAX;
10+
impl Solution {
11+
pub fn coin_change(coins: Vec<i32>, amount: i32) -> i32 {
12+
if amount == 0 {
13+
return 0;
14+
}
15+
let mut dp: HashMap<i32, i32> = HashMap::new();
16+
Self::dfs(&coins, amount, &mut dp)
17+
}
18+
19+
fn dfs(coins: &Vec<i32>, amount: i32, dp: &mut HashMap<i32, i32>) -> i32 {
20+
if amount <= 0 {
21+
return -1;
22+
}
23+
if let Some(r) = dp.get(&amount) {
24+
return *r;
25+
}
26+
27+
for i in coins {
28+
if *i == amount {
29+
return 1;
30+
}
31+
}
32+
33+
let mut result = MAX;
34+
for i in (0..coins.len()).rev() {
35+
let j = Self::dfs(coins, amount - coins[coins.len() - i - 1], dp);
36+
if j != -1 {
37+
result = min(result, j + 1)
38+
}
39+
}
40+
result = if result == MAX { -1 } else { result };
41+
dp.insert(amount, result);
42+
result
43+
}
44+
}
45+
46+
#[cfg(test)]
47+
mod tests {
48+
use super::*;
49+
50+
#[test]
51+
fn test_case0() {
52+
assert_eq!(Solution::coin_change(vec![1, 2, 5], 11), 3);
53+
assert_eq!(Solution::coin_change(vec![2], 3), -1);
54+
}
55+
}

‎src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ mod a0118_pascals_triangle;
2020
mod a0119_pascals_triangle_ii;
2121
mod a0145_binary_tree_postorder_traversal;
2222
mod a0172_factorial_trailing_zeroes;
23+
mod a0322_coin_change;
2324
mod a0392_is_subsequence;
2425
mod a0400_nth_digit;
2526
mod a0404_sum_of_left_leaves;

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /