2011-11-07 2 views
5

다이나믹 코인 변경 문제에 대한 마지막 코드 섹션을 알아 내는데 어려움이 있습니다. 아래 코드를 포함 시켰습니다.동적 프로그래밍 - 변경 만들기

나는 마지막으로 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]; 
} 

답변

2

동전 변경 문제를 해결하기 위해 욕심 많은 알고리즘으로 전환 할 필요가 없으며 동적 프로그래밍 알고리즘으로 해결할 수 있습니다. 예 : 다음과 같이 :

public int minChange(int[] denom, int targetAmount) { 

    int actualAmount; 
    int m = denom.length+1; 
    int n = targetAmount + 1; 
    int inf = Integer.MAX_VALUE-1; 

    int[][] table = new int[m][n]; 
    for (int j = 1; j < n; j++) 
     table[0][j] = inf; 

    for (int denomPosition = 1; denomPosition < m; denomPosition++) { 
     for (int currentAmount = 1; currentAmount < n; currentAmount++) { 
      if (currentAmount - denom[denomPosition-1] >= 0) 
       actualAmount = table[denomPosition][currentAmount - denom[denomPosition-1]]; 
      else 
       actualAmount = inf; 
      table[denomPosition][currentAmount] = Math.min(table[denomPosition-1][currentAmount], 1 + actualAmount); 
     } 
    } 

    return table[m-1][n-1]; 

} 
+1

This는 "targetAmount"를 만들기 위해 필요한 동전의 양입니다. 메서드가 작동하지만 문제에 대한 내 이해를 돕지 않는다. 또는 다른 사람이 denomPosition 및 currentAmount에 대한 for 루프를 보는 코드의 핵심 줄에 주석을 달았지만 원래의 프로그램과 모든 유사점을 잃어 버릴 수 있습니다. 당신의 도움을 주셔서 감사합니다. –

+1

내 구현은 [여기] (http://people.csail.mit.edu/bdean/6.046/dp/)에 설명 된 "변경 중"문제를 기반으로하며 링크에서 동영상을 본 후에는 분명해야합니다. –

0

너는 이것을 생각하고 있니? 미국 동전을 사용하여 68 센트를 바꾸려고한다면 ...

'{25, 10, 5, 1}'이 되겠습니까?

대답은 "2 쿼터, 1 다임, 1 니켈, 3 페니"= '2 + 1 + 1 + 3 = 7'이 아닙니까? 따라서 함수는 값 7을 반환해야합니다. 맞습니까?

+3

배열 denom 될 수있는 예시 denom 대한 값 "코인"의 수를 포함 할 수는 {26, 11, 9, 6, 1} 프로그램의 포인트는 최소 찾는 것이다 target deny가 {10, 6, 1}이고 targetAmount가 12 인 경우 메서드는 3 (10 + 1 + 1) 대신 2 (2x6)를 반환한다고 가정합니다. –

0

실제로이 알고리즘의 올바른 버전입니다.

public static int minChange(int[] denom, int targetAmount) { 
    int actualAmount; 
    int m = denom.length + 1; 
    int n = targetAmount + 1; 
    int inf = Integer.MAX_VALUE - 1; 

    int[][] table = new int[m][n]; 
    for(int i = 0; i< m; ++i) { 
     for (int j = 1; j < n; j++) { 
      table[i][j] = inf; 
     } 
    } 

    for (int denomPosition = 1; denomPosition < m; denomPosition++) { 
     for (int currentAmount = 1; currentAmount < n; currentAmount++) { 
      if (denom[denomPosition-1] <= currentAmount) { 
       // take 
       actualAmount = table[denomPosition][currentAmount - denom[denomPosition-1]]; 
      } 
      else { 
       actualAmount = inf; 
      }            // do not take 
      table[denomPosition][currentAmount] = Math.min(table[denomPosition-1][currentAmount], 1 + actualAmount); 
     } 
    } 

    return table[m-1][n-1]; 
} 
1
//this works perfectly ... 

public int minChange(int[] denom, int targetAmount) 
    { 

    int actualAmount; 
    int m = denom.length+1; 
    int n = targetAmount + 1; 
    int inf = Integer.MAX_VALUE-1; 

    int[][] table = new int[m][n]; 
    for (int j = 1; j < n; j++) 
     table[0][j] = inf; 

    for (int i = 1; i < m; i++) //i denotes denominationIndex 
    { 
     for (int j = 1; j < n; j++) //j denotes current Amount 
     { 
      if (j - denom[i-1] >= 0)//take this denomination value and subtract this value from Current amount 

       table[i][j] = Math.min(table[i-1][j], 1 + table[i][j - denom[i-1]]); 

      else 
       table[i][j] = table[i-1][j]; 

     } 
    } 




    //display array 
     System.out.println("----------------Displaying the 2-D Matrix(denominations and amount)----------------"); 
     for (int i = 0; i < m; i++) 
     { 
      System.out.println(" "); 
      for (int j = 0; j < n; j++) 
      { 
       System.out.print(" "+table[i][j]); 

      } 
      System.out.println(" "); 
     } 

    return table[m-1][n-1]; 

}