Number of ways to make change for amount N

戏子无情 提交于 2019-12-04 02:46:26

Let C(i, j) the number of ways to make the total i using coins of denominations S1, ..., Sj. Your code implements the following recurrence (ordered ways).

C(i, m) | i <  0 = 0
        | i == 0 = 1
        | i >  0 = sum_{j = 1}^m C(i - Sj, m)

The linked code implements a different recurrence (unordered ways).

C(i, j) | i <  0           = 0
        | i == 0           = 1
        | i >  0 && j <= 0 = 0
        | i >  0 && j >  0 = C(i - Sj, j) + C(i, j - 1)

The difference between the two codes is subtle: more or less just how the loops are nested. Yours adds all of the terms for i before moving on to i + 1, but the linked code adds the j term for each i, then the j + 1 term for each i, etc. As a result, when the linked code considers the possibility of using a denomination-Sj coin from subtotal i, it implicitly is considering only those solutions that continue with coins of denominations S1, ..., Sj, because the current total for i - Sj does not include the possibilities that use other coins.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!