Java 理解这个递归函数
我正在修改/改进这个递归函数。我的意图是添加一个全局类变量nrOfFails来存储搜索失败的所有迭代 我按如下方式调用该函数:Java 理解这个递归函数,java,loops,recursion,tail-recursion,Java,Loops,Recursion,Tail Recursion,我正在修改/改进这个递归函数。我的意图是添加一个全局类变量nrOfFails来存储搜索失败的所有迭代 我按如下方式调用该函数: { ArrayList<Integer> solutions = new ArrayList<>(); int[] money1= {2,2,2,5,10,10,20} int targe1 = 24 System.out.print(solutions(money1,target1,solutions)) }
{
ArrayList<Integer> solutions = new ArrayList<>();
int[] money1= {2,2,2,5,10,10,20}
int targe1 = 24
System.out.print(solutions(money1,target1,solutions))
}
/**
* Returns the number of ways of creating specified target value as a sum of money starting with c
* @param money the set of coins
* @param c Index of the array
* @param target the amount to give back
* @return number of ways
*/
private static int solutions(int[] money, int c, int target, ArrayList<Integer> s)
{
assert money!=null : "array should be initialized";
assert c>=0&&c<=money.length;
nrOfFails = 0;
if(target==0)
{
showSolution(s);
return 1;
}
if(target<0)
return 0;
if(c>=money.length)
return 0;
else
{
s.add(money[c]);
int with = solutions(money, c + 1, target - money[c], s);
s.remove(s.size()-1);
int without = solutions(money, c + 1, target,s);
return with + without;
}
}
private static void showSolution(ArrayList<Integer> s)
{
System.out.print(s);
}
{
ArrayList solutions=新的ArrayList();
int[]money1={2,2,2,5,10,10,20}
int targe1=24
系统输出打印(解决方案(money1、target1、解决方案))
}
/**
*返回以c开头的金额创建指定目标值的方法数
*@param money这套硬币
*@param c数组的索引
*@param目标要返还的金额
*@返回方式数
*/
私有静态int解决方案(int[]货币、int c、int目标、ArrayList s)
{
assert money!=null:“应初始化数组”;
断言c>=0 & & c> p>让我们考虑“搜索失败的迭代”,希望计数。
其中一种情况是,将负的target
传递给递归调用(这意味着解决方案中的target-money[c]<0
(money,c+1,target-money[c],s)
递归调用)
另一种情况是在达到目标和之前用完数组元素(即c>=money.length
)
因此,在这两种情况下,您应该增加nrOfFails
计数器。我将它们统一到一个条件中,以缩短代码:
static int nrOfFails = 0;
private static int solutions(int[] money, int c, int target, ArrayList<Integer> s)
{
assert money != null : "array should be initialized";
assert c >= 0 && c <= money.length;
if (target == 0) {
showSolution(s);
return 1;
} else if (target < 0 || c >= money.length) {
nrOfFails++;
return 0;
} else {
s.add(money[c]);
int with = solutions(money, c + 1, target - money[c], s);
s.remove(s.size() - 1);
int without = solutions(money, c + 1, target, s);
return with + without;
}
}
这将产生以下输出:
[2, 2, 10, 10]
[2, 2, 20]
[2, 2, 10, 10]
[2, 2, 20]
[2, 2, 10, 10]
[2, 2, 20]
6
number of fails = 110
[2, 2, 10, 10]
[2, 2, 20]
[2, 2, 10, 10]
[2, 2, 20]
[2, 2, 10, 10]
[2, 2, 20]
6
number of fails = 110