chapter_dynamic_programming/unbounded_knapsack_problem/ #595
Replies: 18 comments 32 replies
-
老师 您好,想请教下,在LeetCode上有个:可以凑成总金额所需的 最少的硬币个数 问题,它动态方程为: |
Beta Was this translation helpful? Give feedback.
-
哈喽,老师,想请教下
总金额为0,感觉应该是没有组合能凑出来,这个1的意思是是空组合吗? |
Beta Was this translation helpful? Give feedback.
-
零钱兑换问题:优化主体是硬币数量而非商品价值,因此在选中硬币时执行+1即可 |
Beta Was this translation helpful? Give feedback.
-
感觉可以增加下:背包类问题的物品和背包遍历的先后性 |
Beta Was this translation helpful? Give feedback.
-
老师,编辑距离问题的时候,步数是要+1的,这里为什么不用+1? |
Beta Was this translation helpful? Give feedback.
-
coins[i - 1] > a 为什么不是 coins[i - 1] != a 呢?恰巧能凑出来金额a的值,才能选择用不选择当前硬币+选择当前硬币的吗? |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
那零钱兑换问题II能不能用类似爬楼梯的思想呢?面值就是爬的步数,target就是层数。 |
Beta Was this translation helpful? Give feedback.
-
作者能否再讲一个背包问题前k优解的问题,我看别人的代码有点看不懂 |
Beta Was this translation helpful? Give feedback.
-
如果最小面值是0.5元,amt+1就不是MAX |
Beta Was this translation helpful? Give feedback.
-
请问对于零钱兑换问题的空间优化为什么要dp = [MAX] * (amt + 1)呢 |
Beta Was this translation helpful? Give feedback.
-
零钱兑换问题2; |
Beta Was this translation helpful? Give feedback.
-
##关于背包问题的遍历顺序有着疑问 |
Beta Was this translation helpful? Give feedback.
-
“在 0-1 背包问题中,每种物品只有一个,因此将物品放入背包后,只能从前i-1个物品中选择。 |
Beta Was this translation helpful? Give feedback.
-
关于零钱兑换问题(非动态规划)的实现,我发现了一个潜在的问题,可能会导致在某些情况下无法正确处理无解的情况。 问题出在初始化和返回值判断部分:
vector<vector<int>> dp(n + 1, vector<int>(amt + 1, 0));
return dp[n][amt] != MAX ? dp[n][amt] : -1; 这样的实现会导致一个问题:如果无法凑出指定金额,dp[n][amt] 就不会被覆盖, 其仍为默认值0,而不是 MAX。这会导致函数错误地返回0,而不是-1。
建议的修改方案:
vector<vector<int>> dp(n + 1, vector<int>(amt + 1, MAX));
for (int i = 0; i <= n; i++) {
dp[i][0] = 0;
}
return dp[n][amt] != MAX ? dp[n][amt] : -1; 这样修改后,当无法凑出指定金额时,dp[n][amt] 将保持为 MAX,函数就能正确返回 -1 表示无解。 |
Beta Was this translation helpful? Give feedback.
-
本节完全背包问题中,在考虑放入物品i的时候,为什么容量约束是c-wgt[i-1]而非c-wgt[i]? |
Beta Was this translation helpful? Give feedback.
-
if (wgt[i - 1] > c) {
// 若超过背包容量,则不选物品 i
dp[c] = dp[c]; // <- ???
} else { 这行是? |
Beta Was this translation helpful? Give feedback.
-
为什么完全背包的问题中,dp[i][j]只能转移到dp[i-1][j]或dp[i][j-wgt[i-1]]+val[i-1]这两种呢?我理解dp[i-1][j]对应本轮放不下i的情况,dp[i][j-wgt[i-1]]+val[i-1]对应本轮能放下且选了i,并且上一次也选了i的情况,那么为什么不存在dp[i-1][j-wgt[i-1]]+val[i-1]来表示本轮能放下且选了i,并且上一次选了i-1的情况呢?dp[i][j]的状态不应该是从dp[i-1][j]、dp[i][j-wgt[i-1]]+val[i-1]、dp[i-1][j-wgt[i-1]]+val[i-1]这三种中选出的最大值吗? |
Beta Was this translation helpful? Give feedback.
-
chapter_dynamic_programming/unbounded_knapsack_problem/
动画图解、一键运行的数据结构与算法教程
https://www.hello-algo.com/chapter_dynamic_programming/unbounded_knapsack_problem/
Beta Was this translation helpful? Give feedback.
All reactions