From 563d43fe7b7e3d10bf0bc53980dfedcabdbdf77f Mon Sep 17 00:00:00 2001 From: Pegasus02K Date: Thu, 14 Apr 2022 12:33:19 +0900 Subject: [PATCH] Create 322-Coin-Change.cpp C++ solution for 322-Coin-Change --- cpp/322-Coin-Change.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 cpp/322-Coin-Change.cpp diff --git a/cpp/322-Coin-Change.cpp b/cpp/322-Coin-Change.cpp new file mode 100644 index 000000000..2b5a37073 --- /dev/null +++ b/cpp/322-Coin-Change.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int coinChange(vector& coins, int amount) { + vector dp(amount + 1, amount + 1); // minimum coin combinations for 0 to amount, set default max value as amount+1(which is impossible to make) + dp[0] = 0; // base case: if amount is 0, 0 coins + for (int a = 1; a <= amount; ++a) { + for (int c : coins) { + if (a - c >= 0) // possible to try + // min of (current min combination, using one for this coin and min of remainder) + dp[a] = min(dp[a], 1 + dp[a - c]); + } + } + return dp[amount] != amount + 1 ? dp[amount] : -1; + } +};