我需要编写一个recusive函数,它接收一个整数num并返回方程的解数:x1 + x2 + x3 = num,其中x1,x2,x31-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);
}
如何在没有重复的情况下获得所需的输出?
慕的地8271018
神不在的星期二
白板的微信
胡子哥哥
森栏
随时随地看视频慕课网APP
相关分类