From 0727149a3aa22eeda93120adc787856e37b5fb66 Mon Sep 17 00:00:00 2001 From: Pegasus02K Date: Thu, 14 Apr 2022 19:55:45 +0900 Subject: [PATCH] Create 518-Coin-Change-2.cpp C++ solution for 518-Coin-Change-2 Similar to NeetCode's 2D DP solution, but differs in order. --- cpp/518-Coin-Change-2.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 cpp/518-Coin-Change-2.cpp diff --git a/cpp/518-Coin-Change-2.cpp b/cpp/518-Coin-Change-2.cpp new file mode 100644 index 000000000..459ff6d96 --- /dev/null +++ b/cpp/518-Coin-Change-2.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int change(int amount, vector& coins) { + vector> dp(coins.size() + 1, vector(amount + 1)); + + // loop with c(number of selected coin types) and a(amount) and the coin value is coins[c-1] + for (int c = 0; c <= coins.size(); ++c) { + int coinVal = c > 0 ? coins[c - 1] : 0; + for (int a = 0; a <= amount; ++a) { + if (a == 0) // amount is 0: only 1 way, which is selecting 0 coin + dp[c][a] = 1; + else if (c == 0) // select 0 coin but amount is not 0: 0 way + dp[c][a] = 0; + else if (coinVal > a) // selected coin(coins[c-1]) is bigger than amount: only can exclude + dp[c][a] = dp[c - 1][a]; + else // include + exclude + dp[c][a] = dp[c][a - coinVal] + dp[c - 1][a]; + } + } + // selecting all possible coins with total amount + return dp[coins.size()][amount]; + } +};