From c8e0c476bdc16e41499940bc1581721bf565f0d9 Mon Sep 17 00:00:00 2001 From: linweibin Date: Sat, 9 Sep 2023 16:28:44 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0C=E7=9A=84=E8=B4=AA=E5=BF=83?= =?UTF-8?q?=E7=AE=97=E6=B3=95=E4=BB=A3=E7=A0=81=20(#726)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- codes/c/CMakeLists.txt | 1 + codes/c/chapter_greedy/CMakeLists.txt | 1 + codes/c/chapter_greedy/coin_change_greedy.c | 60 +++++++++++++++++++++ 3 files changed, 62 insertions(+) create mode 100644 codes/c/chapter_greedy/CMakeLists.txt create mode 100644 codes/c/chapter_greedy/coin_change_greedy.c diff --git a/codes/c/CMakeLists.txt b/codes/c/CMakeLists.txt index 5e583b65..4e5a5d83 100644 --- a/codes/c/CMakeLists.txt +++ b/codes/c/CMakeLists.txt @@ -15,3 +15,4 @@ add_subdirectory(chapter_graph) add_subdirectory(chapter_searching) add_subdirectory(chapter_sorting) add_subdirectory(chapter_backtracking) +add_subdirectory(chapter_greedy) diff --git a/codes/c/chapter_greedy/CMakeLists.txt b/codes/c/chapter_greedy/CMakeLists.txt new file mode 100644 index 00000000..3eb2b8eb --- /dev/null +++ b/codes/c/chapter_greedy/CMakeLists.txt @@ -0,0 +1 @@ +add_executable(coin_change_greedy coin_change_greedy.c) diff --git a/codes/c/chapter_greedy/coin_change_greedy.c b/codes/c/chapter_greedy/coin_change_greedy.c new file mode 100644 index 00000000..9818782a --- /dev/null +++ b/codes/c/chapter_greedy/coin_change_greedy.c @@ -0,0 +1,60 @@ +/** + * File: coin_change_greedy.c + * Created Time: 2023-09-07 + * Author: lwbaptx (lwbaptx@gmail.com) + */ + +#include "../utils/common.h" + +/* 零钱兑换:贪心 */ +int coinChangeGreedy(int* coins, int size, int amt) { + // 假设 coins 列表有序 + int i = size - 1; + int count = 0; + // 循环进行贪心选择,直到无剩余金额 + while (amt > 0) { + // 找到小于且最接近剩余金额的硬币 + while (i > 0 && coins[i] > amt) { + i--; + } + // 选择 coins[i] + amt -= coins[i]; + count++; + } + // 若未找到可行方案,则返回 -1 + return amt == 0 ? count : -1; +} + +/* Driver Code */ +int main() { + // 贪心:能够保证找到全局最优解 + int coins1[6] = {1, 5, 10, 20, 50, 100}; + int amt = 186; + int res = coinChangeGreedy(coins1, 6, amt); + printf("\ncoins = "); + printArray(coins1, 6); + printf("amt = %d\n", amt); + printf("凑到 %d 所需的最少硬币数量为 %d\n", amt, res); + + // 贪心:无法保证找到全局最优解 + int coins2[3] = {1, 20, 50}; + amt = 60; + res = coinChangeGreedy(coins2, 3, amt); + printf("\ncoins = "); + printArray(coins2, 3); + printf("amt = %d\n", amt); + printf("凑到 %d 所需的最少硬币数量为 %d\n", amt, res); + printf("实际上需要的最少数量为 3 ,即 20 + 20 + 20\n"); + + // 贪心:无法保证找到全局最优解 + int coins3[3] = {1, 49, 50}; + amt = 98; + res = coinChangeGreedy(coins3, 3, amt); + printf("\ncoins = "); + printArray(coins3, 3); + printf("amt = %d\n", amt); + printf("凑到 %d 所需的最少硬币数量为 %d\n", amt, res); + printf("实际上需要的最少数量为 2 ,即 49 + 49\n"); + + return 0; +}