fucking-algorithm icon indicating copy to clipboard operation
fucking-algorithm copied to clipboard

bug 动态规划详解进阶 凑零钱问题有误

Open junzew opened this issue 6 years ago • 11 comments

你好,我发现如下文章有 bug(点击文字可跳转到相关文章):

动态规划详解进阶.md

问题描述:

状态转移方程有误

例如coins是[2], 而n是3:

 dp(1) = dp(1-2) + 1 = dp(-1) + 1 = -1 + 1 = 0
 dp(3) = dp(3-2) + 1 = dp(1) + 1 = 0 + 1 = 1

但是dp(3)实际应为-1。

n < 0的case应该把-1改为infinity。

junzew avatar May 20 '20 19:05 junzew

When dp(x) = -1, we skip the problem. As written in his article,

子问题无解,跳过

if subproblem == -1: continue

Besides, what is the meaning of dp(-1)? It is not define and our array does not initialize negative index. Please think about it.

adychn avatar May 21 '20 04:05 adychn

I am not talking about the Python solution or array initialization. All I am saying is that the mathematical representation is a bit inaccurate. dp(-1) is indeed defined by the function dp(n) to be -1, because n can be less than 0.

junzew avatar May 21 '20 05:05 junzew

I see your concern. Yes, the last condition with min {} will cause -1 to be propagated if dp(n) = -1.

adychn avatar May 21 '20 06:05 adychn

回到凑零钱问题,为什么说它符合最优子结构呢?比如你想求 amount = 11 时的最少硬币数(原问题),如果你知道凑出 amount = 10 的最少硬币数(子问题),你只需要把子问题的答案加一(再选一枚面值为 1 的硬币)就是原问题的答案,因为硬币的数量是没有限制的,子问题之间没有相互制,是互相独立的。

不过这一段讲解的确是不对的。11的子问题显然不是10。

Mamong avatar May 25 '20 02:05 Mamong

不过这一段讲解的确是不对的。11的子问题显然不是10。

11的子问题不是11-1=10,11-2=9,和11-5=6吗?

junzew avatar May 25 '20 02:05 junzew

是减少一枚的情况,而不是减少一块的情况

Mamong avatar May 25 '20 06:05 Mamong

n小于0是没有意义的,所以没有探讨的价值。要求n>=0。 所以代码选择跳过,至于状态转移方程,的确应该去掉这种情况。

Mamong avatar May 25 '20 06:05 Mamong

我觉得没毛病啊,问题规模是根据目标金额算的

labuladong avatar Jun 17 '20 12:06 labuladong

不过这一段讲解的确是不对的。11的子问题显然不是10。

这部分表述存在一些问题,有最优子结构没错,不过不是表述中这样

BoyceFong avatar Jun 18 '20 04:06 BoyceFong

他的意思是: coins=[2] amount=5 dp(1) = min(INF, dp(-1)+1) = dp(-1)+1 = 0 dp(3) = min(INF, dp(1)+1)) = 1 dp(5) = min(INF, dp(3)+1) = 2

只是最底层的是-1而不是期望的最终结果dp(5) = -1,这也是 @junzew 想要表达的意思,改成INF能够避免这种问题,INF+1还是INF

h0hmj avatar Jun 24 '20 10:06 h0hmj

好的,我理解了,理论上可以使用 INF,但是编程中用 INT_MAX 的话如果 +1 就会报错,所以用一个足够特殊的值 -1 来表示这种情况。

labuladong avatar Jun 25 '20 04:06 labuladong