Recursively find all coin combinations that produces a specified amount

六眼飞鱼酱① 提交于 2019-12-02 08:07:50
biggestcoin, *rest = coins[0], coins[1:]

You want rest here, logically, not *rest, because you have two items on each side. Using *rest here creates an additional layer of list wrapping, which then results in the exception you're presumably seeing.

Once you fix that: think about what happens if you cannot make the desired amount with 1 of each coin. The change(amount, rest) recursive call will eventually occur with amount being greater than zero, and rest being empty. You need to handle that case as well.

The idea behind recursion is simple:

Try and reduce the size of the problem, one little step at a time.

If you can do that, you're nearly done! Start with the big problem and just keep reducing the size, little by little, until you end up with a very small problem. You can solve that however you like.


How does this apply to the change making problem? Well, if you're asked to make n, you can reduce the size of the problem a little bit by using just one coin. And if you keep going, eventually you will get to a sufficiently-small problem to solve!

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