【问题标题】:change my recursive solution into a dynamic programming solution将我的递归解决方案更改为动态编程解决方案
【发布时间】:2021-08-17 05:49:41
【问题描述】:

我正在尝试将我的递归解决方案转换为动态解决方案,但我在转换时遇到了问题。我正在尝试计算尽可能少的硬币以创造价值。我正在做的是我将所有可能的硬币放入一个向量中,最后在主函数中我会找到我的向量的最小值,这将是我的答案

int rec(vector<int>coins,int n,int sum,int counter)
{
     if(sum==0)
     {
         return 1;
     }
     if(n==0)
     {
         return 0;
     }
     int total=rec(coins,n-1,sum,counter);
     if(sum-coins[n-1]>=0)
     {
         total+=rec(coins,n,sum-coins[n-1],counter+1);
         if(sum-coins[n-1]==0)
         {
              vec.push_back(counter+1);
         }
     }
     return total;
}    

【问题讨论】:

  • 根据硬币的价值,你不需要动态规划,因为贪婪的选择就足够了。

标签: c++ recursion dynamic


【解决方案1】:

你应该先尝试自己解决这类问题。

顺便说一句:

#define BIG 2147483647

int min_coin(int *coins, int m, int desire_value)
{
    int dp[desire_value+1];

    dp[0] = 0;
 
    for (int i=1; i<=desire_value; i++)
        dp[i] = BIG;
 
    for (int i=1; i<=desire_value; i++)
    {
        for (int j=0; j<m; j++)
          if (coins[j] <= i)
          {
              int diff = dp[i-coins[j]];
              if (diff != BIG && diff + 1 < dp[i])
                  dp[i] = diff + 1;
          }
    }
   
      if(dp[desire_value]==BIG)
        return -1;
   
    return dp[desire_value];
}

您可以轻松地将dpcoins 转换为矢量。向量就像数组。(注意为 dp 分配向量,您应该在向量中保留空间,请参阅here。)

【讨论】:

  • 感谢您的回答,但我可以轻松完成您提供的解决方案......但我担心的是在我的 dp 解决方案中调整计数器
猜你喜欢
  • 1970-01-01
  • 2020-06-07
  • 2021-05-06
  • 2013-07-22
  • 1970-01-01
  • 1970-01-01
  • 2015-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多