Optimize Dynamic Programming
Optimize space and remove corner cases
// dp[i][j] number of combinations to make up of amount i with coins[0]:coins[j];
// dp[i][j] = with coins[j] to combine + without coins[j] to combine
public int change(int amount, int[] coins) {
if(amount==0) return 1;
if(coins.length==0) return 0;
int dp[][] = new int[amount+1][coins.length];
for(int i=1; i<=amount; i++) {
for(int j=0;j<coins.length;j++) {
int withCoinJ = 0;
if(i<coins[j]) withCoinJ=0;
else if(i==coins[j]) withCoinJ=1;
else withCoinJ=dp[i-coins[j]][j];
if(j==0) dp[i][0] += withCoinJ; // use coins[j]
else dp[i][j] = withCoinJ+dp[i][j-1]; //without using coins[j]
}
}
return dp[amount][coins.length-1];
}Question:
Reverse thinking: think from end to beginning
Situation
Question:
Last updated