繁体   English   中英

查找最大数量的硬币和选定的硬币

[英]Find Maximum amount of Coins and Selected Coins

我正在做硬币排问题。 我遇到了一个小问题。

有一排 n 个硬币,其值为一些正整数c1, c2, . . . , cn c1, c2, . . . , cn c1, c2, . . . , cn ,不一定不同。

目标是在不能捡起任何两个相邻硬币的限制下捡起最大数量的钱。 例如,在下面的例子中,一旦你拿起10 ,你就不能拿6或左边的2

例子:

enter the number of coins: 6
enter the value of all coins : 5 1 2 10 6 2 
The maximum amount of coin : 17
The selected coins to get maximum value : C1 , C4 , C6

我想获得选定的硬币(例如 C1、C4、C6)。

这是我的功能代码,我只能在此代码中获得最大数量。

int getanswer(int array[],int len)
{
  int C[20];
  for (int j = 0; j < len; j++)
  {
        C[j + 1] = array[j];
  }

  int F[20];
  F[0] = 0;
  F[1] = C[1];

  for (int j = 2; j < len+1; j++)
  {
      F[j] = max(C[j] + F[j - 2], F[j - 1]);
      printf("temp :%d\n", C[j]);
  }

  return F[len];
}

我怎样才能用我的代码获得选定的硬币?

一个好的解决方案将涉及递归、回溯和记忆(动态编程)。 编写一个递归例程,从左端尝试每个可用的选择,然后在剩余的列表上递归。 您当前的算法在其可见范围内有一个不平衡值的盲点(2 个元素)。

这里有一些伪代码可以帮助您入门。

int pickup(coin[])
{
    // base case: <= 2 coins left
    if size(coin) == 0           // return 0 for an empty list
        return 0
    if size(coin) <= 2           // if only 1 or 2 coins left, return the larger
        return max(coin)

    // Otherwise, experiment:
    //   pick *each* of the first two coins, solve the remaining problem,
    //   and compare results.
    pick1 = coin[0] + pickup(coin[2:])      // pick 1st coin; recur on rest of list
    pick2 = coin[1] + pickup(coin[3:])      // pick 2nd coin; recur on rest of list

    return max(pick1, pick2)

这就是总攻。 您可以加快解决了很多与记忆化。 此外,您需要将其转换为您首选的实现语言为此添加跟踪,以便您获得所需的索引。 如果您只需要按顺序返回硬币值,那么累积这些值的数组很简单,每次返回时都预先准备一个。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM