diff --git a/Coin-change-ii.java b/Coin-change-ii.java new file mode 100644 index 00000000..08d914bd --- /dev/null +++ b/Coin-change-ii.java @@ -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]; + + } + +} \ No newline at end of file diff --git a/Paint-house.java b/Paint-house.java new file mode 100644 index 00000000..7d3f6882 --- /dev/null +++ b/Paint-house.java @@ -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; + } +} \ No newline at end of file diff --git a/README.md b/README.md index 4bacf4db..644ab503 100644 --- a/README.md +++ b/README.md @@ -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