diff --git a/coinChange2.cpp b/coinChange2.cpp new file mode 100644 index 00000000..6056751e --- /dev/null +++ b/coinChange2.cpp @@ -0,0 +1,54 @@ +/* ################################################## Recursive Solution ################################################## */ + +class Solution { +public: + int helper(int amount, vector& coins, int idx) + { + if (idx >= coins.size() || amount < 0) { + return 0; + } + + if (amount == 0) { + return 1; + } + + int result = 0; + result += helper(amount - coins[idx], coins, idx); + result += helper(amount, coins, idx + 1); + + return result; + } + int change(int amount, vector& coins) + { + return helper(amount, coins, 0); + } +}; + + +/* ################################################## DP Solution ################################################## */ + + +class Solution { +public: + void helper(vector& dp) + { + for (int i = 1; i < dp.size(); i++) { + dp[i] = 0; + } + + dp[0] = 1; + } + int change(int amount, vector& coins) + { + vectordp(amount + 1, 0); + helper(dp); + + for (int i = 1; i <= coins.size(); i++) { + for (int j = coins[i - 1]; j <= amount; j++) { + dp[j] += dp[j - coins[i - 1]]; + } + } + + return dp[amount]; + } +}; diff --git a/paintHouse.cpp b/paintHouse.cpp new file mode 100644 index 00000000..c8985de4 --- /dev/null +++ b/paintHouse.cpp @@ -0,0 +1,59 @@ +/* ################################################## Recursive Solution ################################################## */ + +class Solution { +public: + int helper (vector>& costs, int i, int col) + { + if (i == costs.size()) { + return 0; + } + + if (col == 0) { + return costs[i][col] + min(helper(costs, i + 1, 1),helper(costs, i + 1, 2)); + } + + if (col == 1) { + return costs[i][col] + min(helper(costs, i + 1, 0),helper(costs, i + 1, 2)); + } + + if (col == 2) { + return costs[i][col] + min(helper(costs, i + 1, 1),helper(costs, i + 1, 0)); + } + + return 0; + } + int minCost(vector>& costs) + { + return min(helper(costs, 0, 0), min(helper(costs, 0, 1), helper(costs, 0, 2))); + } +}; + + +/* ################################################## DP Solution ################################################## */ + +class Solution { +public: + int minCost(vector>& costs) + { + int dp[3]; + + int n = costs.size(); + dp[0] = costs[n - 1][0]; + dp[1] = costs[n - 1][1]; + dp[2] = costs[n - 1][2]; + + for (int i = n - 2; i >= 0; i--) { + int temp0 = dp[0]; + dp[0] = costs[i][0] + min(dp[1], dp[2]); + + int temp1 = dp[1]; + dp[1] = costs[i][1] + min(temp0, dp[2]); + + dp[2] = costs[i][2] + min(temp1, temp0); + } + + return min(dp[0], min(dp[1], dp[2])); + } +}; + +