20240324 Finished

This commit is contained in:
jackfiled 2024-03-24 12:07:56 +08:00
parent b5c93ffb61
commit caa2102e64
2 changed files with 46 additions and 1 deletions

View File

@ -82,4 +82,5 @@ mod p1793_maximum_score_of_a_good_subarray;
mod p1969_minimum_non_zero_product_of_the_array_elements;
mod p2671_frequency_tracker;
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;

View 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));
}
}