Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions Coin-change-ii.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
class Solution {
//recusion approach- exhaustive
public int change(int amount, int[] coins) {
if(coins.length==0 || coins==null) return -1;
return recurse(coins, amount,0);
}
private int recurse(int[] coins, int amount, int index){
//base
if(index == coins.length || amount < 0 ) return 0;
if(amount==0) return 1;
//case0
int case0 = recurse(coins, amount,index+1);
//case1
int case1 = recurse(coins, amount-coins[index], index);

return case0 + case1;


}



//dp approach
public int change(int amount, int[] coins) {
//if(coins.length==0 || coins==null) return -1;
int n = coins.length;
int m = amount;
int[][] dp=new int[n+1][m+1];
dp[0][0] = 1;
for(int i=1;i<=n;i++){
for(int j=0;j<=m;j++){
//denomination > amount
if(coins[i-1]>j){
dp[i][j] = dp[i-1][j];
}else{
//case0 + case1
dp[i][j] = dp[i-1][j] + dp[i][j-coins[i-1]];
}
}
}
return dp[n][m];

}

}
20 changes: 20 additions & 0 deletions Paint-house.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
class Solution {
public int minCost(int[][] costs) {
//final top row elements
int colorR = helper(costs,0, 0);
int colorB = helper(costs,0, 1);
int colorG = helper(costs,0, 2);
return Math.min(colorR, Math.min(colorB, colorG));
}
private int helper(int[][] costs, int idx, int col){ //idx is for house, col is for which color
//base
if(idx == costs.length) return 0; //rows or if there are no houses

//logic
if(col == 0) return costs[idx][0] + Math.min(helper(costs, idx+1, 1), helper(costs, idx+1, 2));
if(col == 1) return costs[idx][1] + Math.min(helper(costs, idx+1, 0), helper(costs, idx+1, 2));
if(col == 2) return costs[idx][2] + Math.min(helper(costs, idx+1, 0), helper(costs, idx+1, 1));

return 868789;
}
}
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
# DP-2

## Problem1(https://leetcode.com/problems/paint-house/)

* paint houses with colors R, B, G such that no 2 houses have same color.
* Greedy - choose min from first row, then choose min from other 2. This fails when 1st choice is wrong. Try exhaustive.
* Keep the last row as it is, the elements will be that sum of that element + min of element of other 2 colors in the below row.


## Problem2 (https://leetcode.com/problems/coin-change-2/)
* indefinite - Return the number of combinations that make up that amount
* if denomination > amount, return from top row
* else that element + smae row element & denomination steps back