gpt4 book ai didi

java - 返回方程 x1 + x2 + x3 = num 的解数

转载 作者:行者123 更新时间:2023-12-02 09:49:24 25 4
gpt4 key购买 nike

我正在尝试编写一个递归方法,该方法接受正整数 num 参数并返回方程的解数

x1 + x2 + x3 = 数字

当三个x为1到10之间的正整数时。该方法还应该打印出这些解决方案,每个解决方案在单独的行中。打印顺序并不重要。

我尝试过:

public static int solutions (int x1, int x2, int x3, int counter, int num)
{
if(x1 > 10 || x2 > 10 || x3 > 10) {
return 0;
}
if (x1 + x2 + x3 == num) {
System.out.println(x1 + "+" + x2 + "+" + x3);
counter = 1;
} else {
return solutions (x1 + 1, x2, x3, counter, num) +
solutions (x1, x2 + 1, x3, counter, num) +
solutions (x1, x2, x3 + 1, counter, num);
}
return counter;
}

public static int solutions (int num)
{
if (num < 3 || num > 30) {
return 0;
}
return solutions (1, 1, 1, 0, num);

}

问题是我重复了结果,问题是我得到了重复的结果,例如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

而不是

1 + 1 + 3
1 + 2 + 2
1 + 3 + 1
2 + 1 + 2
2 + 2 + 1
3 + 1 + 1

如何避免重复两次?

最佳答案

这是我的处理方法:

public static void main(String[] args) {
System.out.println("Number of solutions: "+ solutions(5));
}

public static int solutions(int num)
{
if (num < 3 || num > 30)
return 0;
else
return solutions(num, 1, 1, 1);
}

private static int solutions(int num, int x1, int x2, int x3)
{
int valid = 0;
if (x1 + x2 + x3 == num)
{
valid = 1;
System.out.println(x1 + " + " + x2 + " + " + x3 + " = " + num);
}
if ((x3 < 10) && (x1 + x2 + x3 < num))
{
return valid + solutions(num, x1, x2, ++x3);
}
else if ((x2 < 10) && (x1 + x2 < num))
{
return valid + solutions(num, x1, ++x2, 1);
}
else if ((x1 < 10) && (x1 < num))
{
return valid + solutions(num, ++x1, 1, 1);
}
else
{
return valid;
}
}

关于java - 返回方程 x1 + x2 + x3 = num 的解数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56419262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com