20240324 Finished
This commit is contained in:
parent
b5c93ffb61
commit
caa2102e64
|
@ -83,3 +83,4 @@ mod p1969_minimum_non_zero_product_of_the_array_elements;
|
||||||
mod p2671_frequency_tracker;
|
mod p2671_frequency_tracker;
|
||||||
mod p2617_minimum_number_of_visited_cells_in_a_grid;
|
mod p2617_minimum_number_of_visited_cells_in_a_grid;
|
||||||
mod p2549_count_distinct_numbers_on_board;
|
mod p2549_count_distinct_numbers_on_board;
|
||||||
|
mod p322_coin_change;
|
44
src/problem/p322_coin_change.rs
Normal file
44
src/problem/p322_coin_change.rs
Normal file
|
@ -0,0 +1,44 @@
|
||||||
|
/**
|
||||||
|
* [322] Coin Change
|
||||||
|
*/
|
||||||
|
pub struct Solution {}
|
||||||
|
|
||||||
|
|
||||||
|
// submission codes start here
|
||||||
|
|
||||||
|
impl Solution {
|
||||||
|
pub fn coin_change(coins: Vec<i32>, amount: i32) -> i32 {
|
||||||
|
let amount = amount as usize;
|
||||||
|
let mut dp = vec![i32::MAX; amount + 1];
|
||||||
|
dp[0] = 0;
|
||||||
|
|
||||||
|
for i in 1..=amount {
|
||||||
|
for coin in &coins {
|
||||||
|
let coin = *coin as usize;
|
||||||
|
if coin <= i && dp[i - coin] != i32::MAX {
|
||||||
|
dp[i] = dp[i].min(dp[i - coin] + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return if dp[amount] == i32::MAX {
|
||||||
|
-1
|
||||||
|
} else {
|
||||||
|
dp[amount]
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// submission codes end
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_322() {
|
||||||
|
assert_eq!(3, Solution::coin_change(vec![1,2,5], 11));
|
||||||
|
assert_eq!(-1, Solution::coin_change(vec![2], 3));
|
||||||
|
assert_eq!(0, Solution::coin_change(vec![1], 0));
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user