hello-algo/codes/c/chapter_dynamic_programming/coin_change_ii.c
王作勋 2b59c9ce88
Add Coin change ii in C code (#834)
* Update vector.h

增加功能列表:
获取向量的第 i 个元素
设置向量的第 i 个元素
向量扩容
向量缩容
向量插入元素
向量删除元素
向量交换元素
向量是否为空
向量是否已满
向量是否相等
对向量内部进行排序(升序/降序)
对向量某段数据排序(升序/降序)

* Create hanota.c

* 新增binary_search_recur.c

* Update vector.h

* Delete codes/c/chapter_divide_and_conquer directory

* Update vector.h

* Create binary_search_recur.c

* Delete codes/chapter_divide_and_conquer directory

* Update vector.h

* old vector.h

* Create coin_change_ii.c

* Update coin_change_ii.c

* Create CMakeLists.txt

* Update coin_change_ii.c

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2023-10-07 08:41:09 -05:00

71 lines
1.9 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* File: coin_change_ii.c
* Created Time: 2023-10-02
* Author: Zuoxun (845242523@qq.com)
*/
#include "../utils/common.h"
/* 零钱兑换 II动态规划 */
int coinChangeIIDP(int coins[], int amt, int coinsSize) {
int n = coinsSize;
// 初始化 dp 表
int dp[n + 1][amt + 1];
memset(dp, 0, sizeof(dp));
// 初始化首列
for (int i = 0; i <= n; i++) {
dp[i][0] = 1;
}
// 状态转移
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// 若超过背包容量,则不选硬币 i
dp[i][a] = dp[i - 1][a];
} else {
// 不选和选硬币 i 这两种方案之和
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1]];
}
}
}
return dp[n][amt];
}
/* 零钱兑换 II空间优化后的动态规划 */
int coinChangeIIDPComp(int coins[], int amt, int coinsSize) {
int n = coinsSize;
// 初始化 dp 表
int dp[amt + 1];
memset(dp, 0, sizeof(dp));
dp[0] = 1;
// 状态转移
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// 若超过背包容量,则不选硬币 i
dp[a] = dp[a];
} else {
// 不选和选硬币 i 这两种方案之和
dp[a] = dp[a] + dp[a - coins[i - 1]];
}
}
}
return dp[amt];
}
/* Driver code */
int main() {
int coins[] = {1, 2, 5};
int coinsSize = sizeof(coins) / sizeof(coins[0]);
int amt = 5;
// 动态规划
int res = coinChangeIIDP(coins, amt, coinsSize);
printf("凑出目标金额的硬币组合数量为 %d\n", res);
// 空间优化后的动态规划
res = coinChangeIIDPComp(coins, amt, coinsSize);
printf("凑出目标金额的硬币组合数量为 %d\n", res);
return 0;
}