我無法找出動態變幣問題的最後一段代碼。我已經包含下面的代碼。動態編程 - 製作變化
我想不通最後的else
。我應該在那一點使用貪婪算法還是可以根據表中已有值計算答案?我努力嘗試理解這個問題,我認爲我非常接近。該方法通過創建一個表並使用存儲在表中的結果來解決較大的問題而不使用遞歸來找到進行某種變化所需的最小硬幣數量。
public static int minCoins(int[] denom, int targetAmount){
int denomPosition; // Position in denom[] where the first spot
// is the largest coin and includes every coin
// smaller.
int currentAmount; // The Amount of money that needs to be made
// remainingAmount <= initalAmount
int[][] table = new int[denom.length][targetAmount+1];
for(denomPosition = denom.length-1 ; denomPosition >= 0 ; denomPosition--) {
for(currentAmount = 0 ; currentAmount <= targetAmount ; currentAmount++){
if (denomPosition == denom.length-1){
table[denomPosition][currentAmount] =
currentAmount/denom[denomPosition];
}
else if (currentAmount<denom[denomPosition]){
table[denomPosition][currentAmount] =
table[denomPosition+1][currentAmount];
}
else{
table[denomPosition][currentAmount] =
table[denomPosition+1][currentAmount]-
table[denomPosition][denom[denomPosition]]-1;
}
}
}
return table[0][targetAmount];
}
方法的作品,但無助於我對問題的理解,您或其他人可以評論代碼的關鍵代碼,我看到denomPosition和currentAmount的for循環,但在此之後,它與我的原始程序失去了所有相似之處。謝謝你的幫助。 –
我的實現基於[在此](http://people.csail.mit.edu/bdean/6.046/dp/)中解釋的「正在改變」問題,在鏈接中觀看視頻後應該清楚 –