硬币找零递归方法

编程入门 行业动态 更新时间:2024-10-24 16:21:34
本文介绍了硬币找零递归方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用递归方法来解决硬币找零问题.问题是这样的:

I am trying to solve the coin change problem using a recursive approach. The problem goes like this:

您会得到不同面额的硬币和总金额.编写一个函数来计算组成该数量的组合的数量.

You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount.

为您提供了一定数量的硬币.

You are given an amount and an array of coins.

这是我到目前为止所拥有的:

Here is what I have so far:

private static int[] coins = {1,2,5}; public static void main(String[] args) { System.out.println(count(13)); } public static int count(int n) { // If n is 0 then there is 1 solution if (n == 0) return 1; // If n is less than 0 then no solution exists if (n < 0) return 0; return count(n - coins[0]) + count(n - coins[1]) + count(n - coins[2]); }

执行此操作时,我无法获得正确的组合.我认为问题在于退货,但我不知道为什么.在这里,我从金额中减去硬币,然后每次将它们加在一起.当它为0时,返回1.

When I do this I get nothing close to the right combinations. The problem I think is with the return but I can not figure out why. Here I am subtracting the coin from the amount and adding them together each time. When it gets 0 it returns 1.

推荐答案

首先,您应该替换:

return count(n - coins[0]) + count(n - coins[1]) + count(n - coins[2]);

带有循环:

int nCoins = 0; for(int coin=0; coin<coins.length; coin++) { nCoins += count(n-coins[coin]); } return nCoins;

这样做的麻烦是它将生成硬币的所有排列(= 634).要获得硬币的每种独特组合,您需要确保从当前硬币开始每个递归级别.为此,您需要在count方法中添加一个参数,以指示在钱币数组中开始的位置.

The trouble with this is that it'll generate all permutations of coins (=634). To get each unique combination of coins you need to make sure you start each level of recursion at the current coin. For this you need to add an argument to your count method, to indicate the position in the coin array at which to start.

public static int count(int n, int startCoin)

然后您的循环变为

int nCoins = 0; for(int coin=startCoin; coin<coins.length; coin++) { nCoins += count(n-coins[coin], coin); } return nCoins;

哪个给出正确答案(14).

Which gives the correct answer (14).

更多推荐

硬币找零递归方法

本文发布于:2023-11-02 08:09:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1551847.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   硬币   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!