穷竭搜索:最小硬币数量的变化。使用递归时保留解决方案数组

时间:2012-11-02 16:13:57

标签: c++ recursion

问题在于尽量减少提供确切变化所需的硬币数量。总会有1个可用的硬币,因此问题总会有解决方案。

一些样品硬币套装,其解决方案的金额为40美分:

硬币套装= {1,5,10,20,25},解决方案= {0,0,0,2,0}

硬币套装= {1,5,10,20},解决方案= {0,0,0,2}

实现返回正确的min。硬币数量,但我无法保留正确的解决方案阵列。

int change(int amount, int n, const int* coins, int* solution) {
    if(amount > 0) {
        int numCoinsMin = numeric_limits<int>::max();
        int numCoins;
        int imin;
        for(int i = 0; i != n; ++i) {
            if(amount >= coins[i]) {
                numCoins =  change(amount - coins[i], n, coins, solution) + 1;
                if(numCoins < numCoinsMin) {
                    numCoinsMin = numCoins;
                    imin = i;
                }   
            }   
        }   
        solution[imin] += 1;
        return numCoinsMin;
    }   
    return 0;
}

示例运行:

int main() {
    const int n = 4;
    int coins[n] = {1, 5, 10, 20, 25};
    int solution[n] = {0, 0, 0, 0, 0};
    int amount = 40;

    int min = change(amount, n, coins, solution);
    cout << "Min: " << min << endl;
    print(coins, coins+n); // 1, 5, 10, 20
    print(solution, solution+n); // 231479, 20857, 4296, 199
    return 0;
}

1 个答案:

答案 0 :(得分:0)

你仍然可以使用数组来做到这一点,但是我会改变程序的结构,使它更容易递归。

我将不得不为你做伪代码,因为我几乎不使用C ++,但你可以把它放在一起。这使用了模数除法(C#中的%,如果在C ++中它是相同的dunno,你可以查找它),它只返回除法的余数。在大多数编程语言中,正常除法(/)将返回整数答案并忽略任何余数。

//declare a function that takes in your change amount and the length of your coins array
int changeCounter(int amount, int coins.length)
      int index = coins.length-1;

      //check to see if we're done... again dunno what 'or' is in C++, I put ||

      if (amount <= 0 || index < 0)
         **return** your results array or whatever you want to do here

      //sees how many of the biggest coin there are and puts that number in the results
      if amount > coins[index]
      {
        result[index]= (amount / coins[index])
        //now recurse with the left over coins and drop to the next biggest coin
        changeCounter((amount % coins[index]), index-1)
      }

      //if the amount isnt greater than the coin size then there obviously arent any of that size, so just drop coin sizes and recurse again
      else
         changeCounter(amount,index-1)

这应该让你开始朝着正确的方向前进,我试着为你评论它,我很抱歉我不能为你提供完美的C ++语法,但它不应该太难将我在这里所做的翻译成你的我正试图这样做。

如果您有任何疑问,请告诉我