Commit e489b9cb authored by zhayao's avatar zhayao
Browse files

keep going

parent bdbb481f
......@@ -1684,19 +1684,101 @@ public:
Coin Change
// DP problem, solution 1, bottom up approach
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
if (amount == 0) return 0;
vector<int> table(amount+1, INT_MAX);
vector<int> table(amount+1, amount+1);
table[0] = 0;
for(int i=0; i<table.size(); i++){
for(int i=1; i<table.size(); i++){
for(auto &coin: coins){
if(i >= coin) table[i] = std::min(table[i-coin] + 1, table[i]);
}
}
if (table[amount] > amount) return -1;
return table[amount];
}
};
// DP problem, solution 2, top down approach
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
}
int helper(int used_num, int residious, vector<int>& coins){
if(residious ==0) return 0;
if(residious < 0) return -1;
else{
int min_coins = INT_MAX;
for(int i=0; i<coins.size(); i++){
if(coins[i] <= residious){
int need_coins = used_num+1;
if (helper(used_num+1, residious-coins[i], coins) != -1 ){
}
}
}
}
}
};
public class Solution {
public int coinChange(int[] coins, int amount) {
return coinChange(0, coins, amount);
}
private int coinChange(int idxCoin, int[] coins, int amount) {
if (amount == 0)
return 0;
if (idxCoin < coins.length && amount > 0) {
int maxVal = amount/coins[idxCoin];
int minCost = Integer.MAX_VALUE;
for (int x = 0; x <= maxVal; x++) {
if (amount >= x * coins[idxCoin]) {
int res = coinChange(idxCoin + 1, coins, amount - x * coins[idxCoin]);
if (res != -1)
minCost = Math.min(minCost, res + x);
}
}
return (minCost == Integer.MAX_VALUE)? -1: minCost;
}
return -1;
}
}
public class Solution {
public int coinChange(int[] coins, int amount) {
if (amount < 1) return 0;
return coinChange(coins, amount, new int[amount]);
}
private int coinChange(int[] coins, int rem, int[] count) {
if (rem < 0) return -1;
if (rem == 0) return 0;
if (count[rem - 1] != 0) return count[rem - 1];
int min = Integer.MAX_VALUE;
for (int coin : coins) {
int res = coinChange(coins, rem - coin, count);
if (res >= 0 && res < min)
min = 1 + res;
}
count[rem - 1] = (min == Integer.MAX_VALUE) ? -1 : min;
return count[rem - 1];
}
}
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment