【发布时间】:2019-10-17 07:28:49
【问题描述】:
我需要编写一个 recusive 函数来接收整数 num 并返回方程的解数:x1 + x2 + x3 = num,其中 x1,x2,x3 是 1-10 之间的数字,方法应该打印所有解决方案。
例如,如果num=3,则该方法将打印1+1+1并返回1。
如果num=5,该方法将返回6并打印:
1 + 1 + 3
1 + 2 + 2
1 + 3 + 1
2 + 1 + 2
2 + 2 + 1
3 + 1 + 1
如果num<3 或num>30 方法将返回0。
该方法应该是递归的,不使用循环。不允许使用全局变量。列表也是不允许的。
这是我的代码,它工作正常,但它也会打印重复项,对于 num=5 它会打印:
3 + 1 + 1
2 + 2 + 1
2 + 1 + 2
2 + 2 + 1
1 + 3 + 1
1 + 2 + 2
2 + 1 + 2
1 + 2 + 2
1 + 1 + 3
这是我的代码:
public static void main(String[] args) {
System.out.println("num of solutions: "+solutions(5));
}
public static int solutions(int num)
{
if (num < 3 || num > 30)
return 0;
return solutions(num, 1, 1, 1);
}
private static int solutions(int num, int x1, int x2, int x3)
{
if (x1 < 1 || x1 > 10 || x2 < 1 || x2 > 10||x3 < 1 || x3 > 10)
return 0;
if (x1 + x2 + x3 > num)
return 0;
if (x1 + x2 + x3 == num)
{
System.out.println(x1 + " + " + x2 + " + " + x3);
return 1;
}
return solutions(num, x1 + 1, x2, x3) + solutions(num, x1, x2 + 1, x3) + solutions(num, x1, x2, x3 + 1);
}
如何在不重复的情况下获得所需的输出?
【问题讨论】:
-
您的逻辑可能在某处有错误,但一个hacky修复是只使用
Set。将x1 + " + " + x2 + " + " + x3的每一个字符串放入集合中,打印前检查是否存在。 -
@ChristopherSchneider 我不允许使用 List/Map/Set 等
-
您可以使用 ArrayList
存储 3 个整数的序列,对于每个递归调用检查它是否已经包含该序列。 -
@NeelPatel 我不允许使用 List/Map/Set 等
-
要添加更多,例如,列出这些成员,List={[1,2,2],[1,1,3]} 现在您从递归中获取序列call 是 [1,2,2] 所以这里使用 ArrayList.contains([1,2,2]) 的方法可以消除冗余。
标签: java recursion backtracking